How do I create a incrementing filename in Python?

后端 未结 12 2073
终归单人心
终归单人心 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条回答
  •  萌比男神i
    2020-11-28 06:07

    Try setting a count variable, and then incrementing that variable nested inside the same loop you write your file in. Include the count loop inside the name of the file with an escape character, so every loop ticks +1 and so does the number in the file.

    Some code from a project I just finished:

    numberLoops = #some limit determined by the user
    currentLoop = 1
    while currentLoop < numberLoops:
        currentLoop = currentLoop + 1
    
        fileName = ("log%d_%d.txt" % (currentLoop, str(now())))
    

    For reference:

    from time import mktime, gmtime
    
    def now(): 
       return mktime(gmtime()) 
    

    which is probably irrelevant in your case but i was running multiple instances of this program and making tons of files. Hope this helps!

提交回复
热议问题