Create file but if name exists add number

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

提交回复
热议问题