Remove Blank Lines from a File in Python

To remove blank lines from a file in Python, you can read the file line by line, check for empty or whitespace-only lines, and write the non-blank lines back to another file (or overwrite the original file). This can be done using file handling and string manipulation methods like strip().


Examples

1. Removing Blank Lines Using strip() and Writing to a New File

This method reads a file, removes blank lines, and writes the cleaned content to a new file.

</>
Copy
# Open the input file in read mode
with open("input.txt", "r") as infile:
    # Read all lines and filter out blank lines
    lines = [line for line in infile if line.strip()]

# Open the output file in write mode and write non-blank lines
with open("output.txt", "w") as outfile:
    outfile.writelines(lines)

print("Blank lines removed successfully!")

input.txt

</>
Copy
Sample line 1.

Sample line 2.
Sample line 3.


Sample line 4.



Sample line 5.

Explanation:

In this example:

  1. open("input.txt", "r"): Opens the file in read mode.
  2. lines = [line for line in infile if line.strip()]: Reads each line and filters out empty or whitespace-only lines using strip().
  3. open("output.txt", "w"): Opens a new file (or overwrites if it exists) in write mode.
  4. outfile.writelines(lines): Writes only the non-blank lines to the new file.

Output:

The new file output.txt contains the content without blank lines.

output.txt

</>
Copy
Sample line 1.
Sample line 2.
Sample line 3.
Sample line 4.
Sample line 5.

2. Removing Blank Lines and Overwriting the Same File

If you want to modify the file directly instead of creating a new file, you can overwrite it after removing blank lines.

</>
Copy
# Read lines from the file and filter out blank lines
with open("input.txt", "r") as file:
    lines = file.readlines()

# Write back only non-blank lines
with open("input.txt", "w") as file:
    file.writelines(line for line in lines if line.strip())

print("Blank lines removed and file updated!")

input.txt

</>
Copy
Sample line 1.

Sample line 2.
Sample line 3.


Sample line 4.



Sample line 5.

Explanation:

Here’s how the script works:

  1. file.readlines(): Reads all lines from input.txt into a list.
  2. writelines(line for line in lines if line.strip()): Writes only the non-empty lines back to the same file, effectively removing blank lines.

Output:

The original file is now updated without blank lines.

input.txt

</>
Copy
Sample line 1.
Sample line 2.
Sample line 3.
Sample line 4.
Sample line 5.

3. Removing Blank Lines Using fileinput Module

The fileinput module provides an efficient way to modify a file in place.

</>
Copy
import fileinput

# Modify file in-place
for line in fileinput.input("input.txt", inplace=True):
    if line.strip():
        print(line, end='')

Explanation:

Here’s how it works:

  1. fileinput.input("input.txt", inplace=True): Reads and modifies the file directly.
  2. if line.strip(): Ensures only non-blank lines are printed.
  3. print(line, end=''): Ensures the original formatting is preserved.

Output:

Blank lines removed from file!

The file is modified in place, removing blank lines without creating a new file.

4. Removing Blank Lines Using re (Regular Expressions)

Regular expressions can be used to identify and remove blank lines efficiently.

</>
Copy
import re

# Open file and read content
with open("input.txt", "r") as file:
    content = file.read()

# Remove blank lines using regex
content = re.sub(r"\n\s*\n", "\n", content)

# Write back the modified content
with open("input.txt", "w") as file:
    file.write(content)

print("Blank lines removed using regex!")

Explanation:

Steps explained:

  1. re.sub(r"\n\s*\n", "\n", content): Replaces multiple consecutive blank lines with a single newline.
  2. file.write(content): Saves the modified content back to the file.

Output:

Blank lines removed using regex!

Conclusion

In this tutorial, we covered multiple ways to remove blank lines from a file in Python:

  1. Using strip() and file handling (Recommended for simplicity).
  2. Overwriting the same file for in-place modification.
  3. Using fileinput for efficient in-place editing.
  4. Using re.sub() for regex-based removal of blank lines.