[Tutor] Nested, line by line, file reading

bob gailer bgailer at alum.rpi.edu
Sun Dec 16 14:39:05 CET 2007


jon vs. python wrote:
> Hi everyone,
> I have a file with this content:
>
> "1
> 1
> 1
> 1
> 1
> 1
> 1
> 2
> 1
> 1"
>
> I wanted a little script that would print the line containing "2" and 
> every line containing "1" after it. I've tried this:
>
> >>> def p():
>     f = file("prueba.txt",'r')
>     for startline in f.read():
>         if startline.find("2") != -1:
>             print startline
>             for endline in f.read():
>                 if endline.find("1") != -1:
>                     print endline
>                     break
>     f.close()
>
>    
> >>> p()
> 2
>
> I found a way for doing it.
>
> But still I don't really understand why I don't get two "1" lines 
> printed. It seems that every line is read in "for startline f.read()" 
> so "for endline in f.read()" will start reading but find no data, am I 
> right?
 From the manual: "read([size]) Read at most size bytes from the file 
(less if the read hits EOF before obtaining size bytes). If the size 
argument is negative or omitted, read all data until EOF is reached."

Instead use readline().

Then realize that will also consume the entire file, so a nested 
readline() will return "".



More information about the Tutor mailing list