Newline at EOF Removal
bokr at oz.net
Mon Jan 9 04:51:19 CET 2006
On Sun, 08 Jan 2006 17:10:01 -0600, "Alex Nordhus" <megahrtz at gte.net> 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?
>f = open("oldfile.txt")
>w = open("newfile.txt", "wt")
>for line in f.readlines():
> line = re.sub(r'^\s+$', '', line)
>I have tried everything I know and still falling short. Any help?
First, you don't need re for that, and second, why write a zero-length ''?
It might even confuse some file system. You don't need readlines either. Try
# open f and w as before 
for line in f:
if line.strip(): w.write(line) # write only non-blank lines
 BTW, I didn't see the 't' mode in http://docs.python.org/lib/built-in-funcs.html
description of open/file, but I have a nagging doubt about saying it's not valid.
Where did you see it?
More information about the Python-list