faqts : Computers : Programming : Languages : Python : Snippets : Stream Manipulation : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

26 of 34 people (76%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

Python routine to remove blank lines from a text file

Sep 18th, 2000 21:54
unknown unknown, Alex Martelli, Tyler Eaves, Jeremy Hylton


out = open(r'C:\bar.txt', 'w')
for line in open(r'c:\foo.txt').readlines():
    if len(line)>1:
        out.write(line)
out.close()
Notes:
    we can use the r'string' notation to let backslashes (\) be
    used in a platform-natural way on Windows, without doubling
    them up (we could also write 'c:/foo.txt', etc);
    we don't need an explicitly named object for the input-file,
    as we just get its list-of-lines in the for statement itself;
    thus, we don't need to close it, either (it is automatically
    closed by the Python runtime as soon as possible & convenient).
----- Alternatively ------
import fileinput
f = open("c:\\bar.txt", "w")
for line in fileinput.input("c:\\foo.txt"):
    if not line.startswith("\n"):
        f.write(line)
f.close()
If I could modify the behavior a bit, I would: (1) make it skip any
non-blank line that only has whitespace and (2) have it edit the file
in place. 
import fileinput
for line in fileinput.input("c:\\foo.txt", inplace=1):
    if line.strip():
        f.write(line)
f.close()