[Tutor] Nested, line by line, file reading
Kent Johnson
kent37 at tds.net
Sun Dec 16 15:33:21 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():
As Bob pointed out, f.read() reads the entire file into a single string.
Iterating over a string yields individual characters, not lines. So
startline is actually a single character.
> if startline.find("2") != -1:
More simply:
if "2" in startline:
Kent
More information about the Tutor
mailing list