readline in while loop

Steven Taschuk staschuk at telusplanet.net
Fri May 23 10:50:06 EDT 2003


Quoth Geert Fannes:
> 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?

What do you want to happen when one of the files ends?  Here's a
simple (though verbose) answer for if you want the loop to stop
when the shorter file stops:

    f1 = file('file1')
    f2 = file('file2')
    while True:
        line1 = f1.readline()
        line2 = f2.readline()
        if not line1:
            break
        if not line2:
            break
        print line1, line2

(Note, btw, that you don't need semicolons as statement
terminators in Python, and it is bad style to use them
unnecessarily.)

This can be made terser and more expressive by using iterators and
the (new in 2.3) itertools module:

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

In 2.2.2 without the itertools module, you could write izip
yourself:

    from __future__ import generators

    def izip(iterable1, iterable2):
        iter1 = iter(iterable1)
        iter2 = iter(iterable2)
        while True:
            yield iter1.next(), iter2.next()

(This stops when either .next call raises a StopIteration
exception, and that exception propagates to the caller, to
indicate that this iterator is done.  Note, btw, that the
itertools.izip handles any number of arguments, unlike this mock
version.  Fixing this is left as an exercise.)

-- 
Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1





More information about the Python-list mailing list