readline in while loop

Alex Martelli aleaxit at yahoo.com
Fri May 23 10:12:26 EDT 2003


Geert Fannes wrote:

> i'm indeed a C++ programmer. then i have another question: suppose i
> have 2 files and i want to read from both of them. things like this do
> not work:
> 
> f1=file("file1","r");
> f2=file("file2","r");
> for line1 in f1 and line2 in f2:
> print line1,line2;
> 
> any idea how i can solve this?

In 2.3,

import itertools

for line1, line2 in itertools.izip(f1, f2):
    print line1, line2

should do exactly what you want (if one file has fewer lines
than the other, this will stop at the length of the shorter).

In earlier releases, without itertools, you'd have to accept
the fact that everything is put in memory at once:

for line1, line2 in zip(f1, f2):
    print line1, line2

or else break the simmetry between the files, e.g.:

iterfile2 = iter(f2)
for line1 in f1:
    line2 = iterfile2.next()
    print line1, line2

(this would fail with a StopIteration exception of file2 had
fewer lines than file1 -- that can of course be fixed but how
to fix it depends on what you're after!) or go for a different
control structure such as:

while 1:
    line1 = f1.readline()
    line2 = f2.readline()
    if not line1 or not line2: break
    print line1, line2


Alex





More information about the Python-list mailing list