Newline at EOF Removal

Alex Nordhus megahrtz at gte.net
Mon Jan 9 00:10:01 CET 2006



I am looking for a way to strip the blank line and the empty newline at
the end of the text file. I can get the blank lines removed from the
file but it always leaves the end line (which is blank) as a newline. My
code is here and it works but leaves the newline at the end of the file.
How do I get rid of it?

import re
f = open("oldfile.txt")
w = open("newfile.txt", "wt")
for line in f.readlines():
    line = re.sub(r'^\s+$', '', line)


    w.write(line)

w.close()

I have tried everything I know and still falling short. Any help?




More information about the Python-list mailing list