strip newlines and blanks

Fredrik Lundh fredrik at pythonware.com
Tue May 2 09:15:49 CEST 2006


micklee74 at hotmail.com wrote:

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

assuming you want to skip *all* blank lines (even if they have whitespace
on them),

    for line in open("test.dat"):
        if line.strip():
            print line

</F>






More information about the Python-list mailing list