reading file objects in chunks

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Nov 12 12:07:05 EST 2007


On Mon, 12 Nov 2007 17:47:29 +0100, Martin Marcher wrote:

> I'd really like something nicer than
> 
> chunksize = 26
> f = file("datafile.dat", buffering=chunksize)
> 
> chunk = f.read(chunksize)
> while len(chunk) == chunksize:
>   compute_data(chunk)
>   f.read(chunksize)
> 
> I just don't feel comfortable with it for some reason I can't explain...

chunksize = 26
f = open('datafile.dat', 'rb')
for chunk in iter(lambda: f.read(chunksize), ''):
    compute_data(chunk)
f.close()

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list