Create file but if name exists add number

后端 未结 14 1966
醉话见心
醉话见心 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
    
    0 讨论(0)
  • 2020-12-04 19:10

    recently I encountered the same thing and here is my approach:

    import os
    
    file_name = "file_name.txt"
    if os.path.isfile(file_name):
        expand = 1
        while True:
            expand += 1
            new_file_name = file_name.split(".txt")[0] + str(expand) + ".txt"
            if os.path.isfile(new_file_name):
                continue
            else:
                file_name = new_file_name
                break
    
    0 讨论(0)
提交回复
热议问题