Create file but if name exists add number

后端 未结 14 2005
醉话见心
醉话见心 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条回答
  •  Happy的楠姐
    2020-12-04 18:48

    I found that the os.path.exists() conditional function did what I needed. I'm using a dictionary-to-csv saving as an example, but the same logic could work for any file type:

    import os 
    
    def smart_save(filename, dict):
        od = filename + '_' # added underscore before number for clarity
    
        for i in np.arange(0,500,1): # I set an arbitrary upper limit of 500
            d = od + str(i)
    
            if os.path.exists(d + '.csv'):
                pass
    
            else:
                with open(d + '.csv', 'w') as f: #or any saving operation you need
                    for key in dict.keys():
                        f.write("%s,%s\n"%(key, dictionary[key]))
                break
    

    Note: this appends a number (starting at 0) to the file name by default, but it's easy to shift that around.

提交回复
热议问题