Create file but if name exists add number

后端 未结 14 2010
醉话见心
醉话见心 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:50

    I ended up writing my own simple function for this. Primitive, but gets the job done:

    def uniquify(path):
        filename, extension = os.path.splitext(path)
        counter = 1
    
        while os.path.exists(path):
            path = filename + " (" + str(counter) + ")" + extension
            counter += 1
    
        return path
    

提交回复
热议问题