Is this the best way to get unique version of filename w/ Python?

前端 未结 6 820
情话喂你
情话喂你 2021-02-05 12:36

Still \'diving in\' to Python, and want to make sure I\'m not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files t

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 13:13

    How about

    def ensure_unique_filename(orig_file_path):    
        from time import time
        import os
    
        if os.path.lexists(orig_file_path):
            name, ext = os.path.splitext(orig_file_path)
            orig_file_path = name + str(time()).replace('.', '') + ext
    
        return orig_file_path
    

    time() returns current time in milliseconds. combined with original filename, it's fairly unique even in complex multithreaded cases.

提交回复
热议问题