How do I create a incrementing filename in Python?

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

    The two ways to do it are:

    1. Check for the existence of the old file and if it exists try the next file name +1
    2. save state data somewhere

    an easy way to do it off the bat would be:

    import os.path as pth
    filename = "myfile"
    filenum = 1
    while (pth.exists(pth.abspath(filename+str(filenum)+".py")):
        filenum+=1
    my_next_file = open(filename+str(filenum)+".py",'w')
    

    as a design thing, while True slows things down and isn't a great thing for code readability


    edited: @EOL contributions/ thoughts

    so I think not having .format is more readable at first glance - but using .format is better for generality and convention so.

    import os.path as pth
    filename = "myfile"
    filenum = 1
    while (pth.exists(pth.abspath(filename+str(filenum)+".py")):
        filenum+=1
    my_next_file = open("{}{}.py".format(filename, filenum),'w')
    # or 
    my_next_file = open(filename + "{}.py".format(filenum),'w')
    

    and you don't have to use abspath - you can use relative paths if you prefer, I prefer abs path sometimes because it helps to normalize the paths passed :).

    import os.path as pth
    filename = "myfile"
    filenum = 1
    while (pth.exists(filename+str(filenum)+".py"):
        filenum+=1
    ##removed for conciseness
    

提交回复
热议问题