strip newlines and blanks

Peter Otten __peter__ at web.de
Tue May 2 03:09:43 EDT 2006


micklee74 at hotmail.com wrote:

Mick, you should be a bit more patient. Allow for some time for an answer to
arrive. Minor edits of your question don't warrant a repost.

> i have a file test.dat eg
> 
> abcdefgh
> ijklmn
>          <-----newline
> opqrs
> tuvwxyz
> 
> 
> I wish to print the contents of the file such that it appears:
> abcdefgh
> ijklmn
> opqrs
> tuvwxyz
> 
> here is what i did:
> f = open("test.dat")
> while 1:
>         line = f.readline().rstrip("\n")
>         if line == '':
>                 break
>         print line
> 
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
> 
> What can i do to make it print all w/o the newlines..? and what is the
> proper way to skip printing blank lines while iterating file contents?

The end of the file is signalled by an empty string, and a blank line with
the trailing "\n" stripped off is an empty string, too. Therefore you have
to perform the line == '' test before the stripping.

Here's an alternative approach:

for line in f:
    line = line.rstrip()
    if line: 
        print line

This will ignore any lines containing only whitespace and remove trailing
whitespace from the non-white lines.

Peter
     
    



More information about the Python-list mailing list