simultaneous reading and writing a textfile

Peter Otten __peter__ at
Wed May 17 11:38:08 CEST 2006

Mark Wilkinson wrote:

> Why this:
>> lines = iter(infile.readline, "")
>> # copy one line at a time
>> for line in lines:
> Rather than this?
>> for line in infile: uses an internal cache. The data in that cache would be lost
when the rest of the file is copied using with

for block in iter(lambda:, ""):


>>> open("tmp.txt", "w").write("alpha\nbeta\ngamma\n")
>>> infile = open("tmp.txt")
'' # where is 'beta\ngamma\n'?

I admit I didn't profile whether the suggested approach is an overall win
over line-wise copying of the whole file or manually keeping track of the
position in the file followed by a seek().


More information about the Python-list mailing list