Newline at EOF Removal

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


"Alex Nordhus" <megahrtz at gte.net> 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
http://www.mired.org/home/mwm/spare/ ); simple string methods can do
this job for you. Try:

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



       <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list