How do I create an incrementing filename

file-io, python

Solution

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.

Problem

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() ```

Original source

Related problems