如何在Python中创建递增的文件名? [英] How do I create an incrementing filename in Python?
问题描述
我正在创建一个程序,该程序将创建一个文件并将其保存为文件名sample.xml.当我再次尝试运行该程序时,一旦文件被保存,它会将旧文件覆盖为新文件,因为它们确实具有相同的文件名.如何增加文件名,以便每当我再次尝试运行代码时,都会增加文件名.并且不会覆盖现有的.我正在考虑先检查目录中的文件名,如果它们相同,代码将生成一个新的文件名:
I'm creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it overwrites the old file into the new one because they do have the same file name. How do I increment the file names so that whenever I try to run the code again it will going to increment the file name. and will not overwrite the existing one. I am thinking of checking the filename first on the directory and if they are the same the code will generate a new filename:
fh = open("sample.xml", "w")
rs = [blockresult]
fh.writelines(rs)
fh.close()
推荐答案
例如,我将遍历 sample [int] .xml
并获取文件或文件未使用的下一个可用名称.目录.
I would iterate through sample[int].xml
for example and grab the next available name that is not used by a file or directory.
import os
i = 0
while os.path.exists("sample%s.xml" % i):
i += 1
fh = open("sample%s.xml" % i, "w")
....
最初应该为您提供 sample0.xml ,然后为您提供 sample1.xml ,依此类推.
That should give you sample0.xml initially, then sample1.xml, etc.
请注意,默认情况下,相对文件表示法与您从中运行代码的文件目录/文件夹有关.如有必要,请使用绝对路径.使用 os.getcwd()
读取您的当前目录,并使用 os.chdir(path_to_dir)
设置新的当前目录.
Note that the relative file notation by default relates to the file directory/folder you run the code from. Use absolute paths if necessary. Use os.getcwd()
to read your current dir and os.chdir(path_to_dir)
to set a new current dir.
这篇关于如何在Python中创建递增的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!