Create file but if name exists add number

后端 未结 14 2030
醉话见心
醉话见心 2020-12-04 18:08

Does Python have any built-in functionality to add a number to a filename if it already exists?

My idea is that it would work the way certain OS\'s work - if a file

14条回答
  •  感动是毒
    2020-12-04 18:56

    If all files being numbered isn't a problem, and you know beforehand the name of the file to be written, you could simply do:

    import os
    
    counter = 0
    filename = "file{}.pdf"
    while os.path.isfile(filename.format(counter)):
        counter += 1
    filename = filename.format(counter)
    

提交回复
热议问题