[Tutor] Nested, line by line, file reading
Alan Gauld
alan.gauld at btinternet.com
Sun Dec 16 16:12:46 CET 2007
"jon vs. python" <jonvspython at gmail.com> wrote in
> 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()
Its easier to iterate over the file itself
found2 = False
for line in file("prueba.txt"):
if '2' in line: found2 = True
if found2: print line
else: continue
Should be close.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list