[Python-ideas] itertools.chunks()
Antoine Pitrou
solipsis at pitrou.net
Wed Apr 10 10:41:18 CEST 2013
Le Sat, 6 Apr 2013 14:50:16 +0200,
Giampaolo Rodolà <g.rodola at gmail.com> a
écrit :
> def chunks(total, step):
> assert total >= step
> while total > step:
> yield step;
> total -= step;
> if total:
> yield total
>
> >>> chunks(12, 4)
> [4, 4, 4]
> >>> chunks(13, 4)
> [4, 4, 4, 1]
>
> I'm not sure how appropriate "chunks" is as a name for such a
> function. Anyway, I wrote that because in a unit test I had to create
> a file of a precise size, like this:
>
> FILESIZE = (10 * 1024 * 1024) + 423 # 10MB and 423 bytes
> with open(TESTFN, 'wb') as f:
> for csize in chunks(FILESIZE, 262144):
> f.write(b'x' * csize)
This doesn't sound very useful to me, actually. range() already does
what you want, except for the "last chunk" thing.
Regards
Antoine.
More information about the Python-ideas
mailing list