strip newlines and blanks

Kent Johnson kent at kentsjohnson.com
Tue May 2 07:54:48 EDT 2006


micklee74 at hotmail.com wrote:
> hi
> 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

break terminates the loop, so no more lines will be processed. Use 
continue, which ends only the current iteration of the loop. (Though you 
will need a separate test to terminate the loop when there are no more 
lines.)

You can iterate an open file directly; here is a shorter version:

for line in open('test.dat'):
   line = line.rstrip('\n')
   if line:
     print line

Kent

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



More information about the Python-list mailing list