Newline at EOF Removal

Mike Meyer mwm at
Mon Jan 9 04:25:29 CET 2006

"Alex Nordhus" <megahrtz at> writes:
> 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.

This really isn't a very clear description of the problem. Does your
file end with two newlines in row? That would be what you'd get if it
ended with the newline for the last line. If it ends with just one
newline, then you're not getting the a blank last line, you're simply
getting a last line that ends with a newline.

> 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)

This is an abuse of regular expressions (see ); simple string methods can do
this job for you. Try:

for line in f:
    if line.strip():

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list