stripping

Tim Williams tdw at tdw.net
Tue May 2 06:51:06 EDT 2006


On 1 May 2006 23:20:56 -0700, micklee74 at hotmail.com <micklee74 at hotmail.com>
wrote:
>
> hi
> i have a file test.dat eg
>
> abcdefgh
> ijklmn
>          <-----newline
> opqrs
> tuvwxyz
>           <---newline
>
>
> 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
>         #if not re.findall(r'^$',line):
>         print line
>
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
>
> What can i do to make it print all..?


The break is terminating the while loop after the first blank line,
replacing it with a continue would solve the problem in your script.

However:

f = open("test.dat")
while 1:
        line = f.readline().rstrip("\n")
        if line:
             print line

is simpler and easier to read.   And:

>>> f = open("test.dat").read()  # read the whole file at once into string f
>>> print f.replace('\n\n','\n')
abcdefgh
ijklmn
opqrs
tuvwxyz

>>>

even simpler,  as long as the file isn't huge.

If you need the final newline removed, use:

>>>print f.replace('\n\n','\n')[:-1]
abcdefgh
ijklmn
opqrs
tuvwxyz
>>>

HTH :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060502/ddcc69b8/attachment.html>


More information about the Python-list mailing list