Question

So the text file I have is formatted something like this:

a

b

c

I know how to strip() and rstrip() but I want to get rid of the empty lines. I want to make it shorter like this:

a 
b
c
Was it helpful?

Solution

You could remove all blank lines (lines that contain only whitespace) from stdin and/or files given at the command line using fileinput module:

#!/usr/bin/env python
import sys
import fileinput

for line in fileinput.input(inplace=True):
    if line.strip(): # preserve non-blank lines
        sys.stdout.write(line)

OTHER TIPS

You can use regular expressions :

import re

txt = """a

b

c"""

print re.sub(r'\n+', '\n', txt) # replace one or more consecutive \n by a single one

However, lines with spaces won't be removed. A better solution is :

re.sub(r'(\n[ \t]*)+', '\n', txt)

This way, wou will also remove leading spaces.

Simply remove any line that only equals "\n":

in_filename = 'in_example.txt'
out_filename = 'out_example.txt'

with open(in_filename) as infile, open(out_filename, "w") as outfile:
    for line in infile.readlines():
        if line != "\n":
            outfile.write(line)

If you want to simply update the same file, close and reopen it to overwrite it with the new data:

filename = 'in_example.txt'
filedata = ""

with open(filename, "r") as infile:
    for line in infile.readlines():
        if line != "\n":
            filedata += line

with open(filename, "w") as outfile:
    outfile.write(filedata)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top