Create file but if name exists add number

后端 未结 14 1990
醉话见心
醉话见心 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 19:08

    Let's say I already have those files:

    This function generates the next available non-already-existing filename, by adding a _1, _2, _3, etc. suffix before the extension if necessary:

    import os
    
    def nextnonexistent(f):
        fnew = f
        root, ext = os.path.splitext(f)
        i = 0
        while os.path.exists(fnew):
            i += 1
            fnew = '%s_%i%s' % (root, i, ext)
        return fnew
    
    print(nextnonexistent('foo.txt'))  # foo_3.txt
    print(nextnonexistent('bar.txt'))  # bar_1.txt
    print(nextnonexistent('baz.txt'))  # baz.txt
    

提交回复
热议问题