Newline at EOF Removal

Peter Hansen peter at engcorp.com
Sun Jan 8 21:57:15 EST 2006


Alex Nordhus wrote:
> 
> 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?

If you want to remove all blank lines at the end of the file, but leave 
a single newline following the last non-blank line, this might be the 
simplest thing to try:

w.write(f.read().rstrip('\n') + '\n')

Of course, that requires reading in all the data in one swell foop, but 
that's usually not a problem.  It also technically fails in the special 
case of a file that has only blank lines (since it will result in a file 
with a single newline) but your specification is ambiguous about what 
you want to do in that case anyway.

This also depends on the definition of "blank" being "empty line", which 
  might not be how you define it.  Are you trying to remove lines that 
contain only whitespace?  (Note that whitespace is usually considered to 
include "\x20\r\n\t\f\v".)

-Peter




More information about the Python-list mailing list