correct usage of a generator?

Neil Cerutti neilc at norwich.edu
Mon Nov 28 12:04:25 EST 2011


On 2011-11-28, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Mon, 28 Nov 2011 07:36:17 -0800, Tim wrote:
>> Hi, I need to generate a list of file names that increment, like this:
>> fname1
>> fname2
>> fname3 and so on.
>> 
>> I don't know how many I'll need until runtime so I figure a
>> generator is called for.
>> 
>> def fname_gen(stem):
>>     i = 0
>>     while True:
>>         i = i+1
>>         yield '%s%d' % (stem,i)
>> 
>> blarg = fname_gen('blarg')
>> boo = fname_gen('boo')

I don't see anything wrong with that. I've written similar code
in terms of itertools.count, myself. If I may make a suggestion,
it would be nice to zero-pad the number to achieve
lexicographical ordering of filenames. However, if you really
have no idea of the magnitude you might need that won't work. The
following assumes you'll need less than 1000.

counter = itertools.count()
...
with open("%03d" % counter.next(), "w") as the_next_file:
  ...

My Python < 3.0 is rusty, so sorry if I messed that up.

-- 
Neil Cerutti



More information about the Python-list mailing list