How do I create a incrementing filename in Python?

后端 未结 12 2098
终归单人心
终归单人心 2020-11-28 05:45

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 over

12条回答
  •  误落风尘
    2020-11-28 06:14

    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.

提交回复
热议问题