[Tutor] Reading & printing lines from two different files
Scot W. Stevenson
scot@possum.in-berlin.de
Fri, 7 Jun 2002 08:54:04 +0200
Hi there,=20
Danny Yoo wrote:
> (If the files are actually much longer, we might not need to abandon
> this appraoch: we can use a variation of the zip() function by using
> Python 2.2 generators that's less of a memory hog.)
Would this be something like:
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D
from __future__ import generators
file_one =3D 'text1.txt'
file_two =3D 'text2.txt'
def generate_line(filename):
thisfile =3D open(filename, 'r')
for line in thisfile:
yield line
gen_one =3D generate_line(file_one)
gen_two =3D generate_line(file_two)
while 1:
try:
print gen_one.next()
print gen_two.next()
except StopIteration:
break
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D
This does work here, tho it seems like an awful lot of code compared with=
=20
your zip-and-readlines combination. Is there any simple way to explain wh=
y=20
this is not such a memory hog?
One thing I'm not sure of in the example above is where to put the=20
thisfile.close() line to close those files again. My computer doesn't see=
m=20
any worse for not closing them, but it does seem like bad manners...
Y, Scot
--=20
Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany