且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中创建一个递增的文件名?

更新时间:2022-10-15 11:54:48

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")
....

That should give you sample0.xml initially, then sample1.xml, etc.

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.