How do you increment a file name in Python

I am trying to save a lot of data that needs to be divided into different files, for example data_1.dat data_2.dat data_3.dat data_4.dat

how to implement this in python?

+4
source share
4 answers
for i in range(10): filename = 'data_%d.dat'%(i,) print filename 
+9
source
 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' 
+9
source

Similar to Sven's solution, but before the 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 
0
source

If you are following the itertools path, why mix it with a generator expression?

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

Source: https://habr.com/ru/post/1340650/


All Articles