Create file but if name exists add number

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

    This works for me. The initial file name is 0.yml, if it exists, it will add one until meet the requirement

    import os
    import itertools
    
    def increment_filename(file_name):
        fid, extension = os.path.splitext(file_name)
    
        yield fid + extension
        for n in itertools.count(start=1, step=1):
            new_id = int(fid) + n
            yield "%s%s" % (new_id, extension)
    
    
    def get_file_path():
        target_file_path = None
        for file_name in increment_filename("0.yml"):
            file_path = os.path.join('/tmp', file_name)
            if not os.path.isfile(file_path):
                target_file_path = file_path
                break
        return target_file_path
    

提交回复
热议问题