How do I create a incrementing filename in Python?

后端 未结 12 2067
终归单人心
终归单人心 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:06

    You can use a while loop with a counter which checks if a file with a name and the counter's value exists if it does then move on else break and make a file.

    I have done it in this way for one of my projects:`

    from os import path
    import os
    
    i = 0
    flnm = "Directory\\Filename" + str(i) + ".txt"
    while path.exists(flnm) :
        flnm = "Directory\\Filename" + str(i) + ".txt"
        i += 1
    f = open(flnm, "w") #do what you want to with that file...
    f.write(str(var))
    f.close() # make sure to close it.
    

    `

    Here the counter i starts from 0 and a while loop checks everytime if the file exists, if it does it moves on else it breaks out and creates a file from then you can customize. Also make sure to close it else it will result in the file being open which can cause problems while deleting it. I used path.exists() to check if a file exists. Don't do from os import * it can cause problem when we use open() method as there is another os.open() method too and it can give the error. TypeError: Integer expected. (got str) Else wish u a Happy New Year and to all.

提交回复
热议问题