开发者

How do you increment file name in Python

开发者 https://www.devze.com 2023-02-12 23:52 出处:网络
I\'m trying to save a lot of data that needs to be separated in to different files like so data开发者_JAVA百科_1.dat

I'm trying to save a lot of data that needs to be separated in to different files like so data开发者_JAVA百科_1.dat data_2.dat data_3.dat data_4.dat

how do I implement this in python?


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'


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


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


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'
0

精彩评论

暂无评论...
验证码 换一张
取 消