chutsu
chutsu

Reputation: 14103

How do you increment file name in Python

I'm trying to save a lot of data that needs to be separated in to different files like so data_1.dat data_2.dat data_3.dat data_4.dat

how do I implement this in python?

Upvotes: 6

Views: 17312

Answers (4)

tzot
tzot

Reputation: 95921

If you go the itertools way, why mix it with a generator expression?

>>> import itertools as it
>>> fngen= it.imap("file%d".__mod__, it.count(1))
>>> next(fngen)
'file1'

Upvotes: 0

ncoghlan
ncoghlan

Reputation: 41486

Similar to Sven's solution, but upgrading to a full generator:

from itertools import count
def gen_filenames(prefix, suffix, places=3):
    """Generate sequential filenames with the format <prefix><index><suffix>

       The index field is padded with leading zeroes to the specified number of places
    """
    pattern = "{}{{:0{}d}}{}".format(prefix, places, suffix)
    for i in count(1):
        yield pattern.format(i)

>>> g = gen_filenames("data_", ".dat")
>>> for x in range(3):
...     print(next(g))
... 
data_001.dat
data_002.dat
data_003.dat

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601599

from itertools import count
filename = ("data_%03i.dat" % i for i in count(1))
next(filename)
# 'data_001.dat'
next(filename)
# 'data_002.dat'
next(filename)
# 'data_003.dat'

Upvotes: 13

yan
yan

Reputation: 20982

for i in range(10):
    filename = 'data_%d.dat'%(i,)
    print filename

Upvotes: 9

Related Questions