Best way to generate random file names in Python

前端 未结 11 2086
囚心锁ツ
囚心锁ツ 2020-12-04 08:48

In Python, what is a good, or the best way to generate some random text to prepend to a file(name) that I\'m saving to a server, just to make sure it does not overwrite. Tha

11条回答
  •  一生所求
    2020-12-04 09:29

    If you want to preserve the original filename as a part of the new filename, unique prefixes of uniform length can be generated by using MD5 hashes of the current time:

    from hashlib import md5
    from time import localtime
    
    def add_prefix(filename):
        prefix = md5(str(localtime()).encode('utf-8')).hexdigest()
        return f"{prefix}_{filename}"
    

    Calls to the add_prefix('style.css') generates sequence like:

    a38ff35794ae366e442a0606e67035ba_style.css
    7a5f8289323b0ebfdbc7c840ad3cb67b_style.css
    

提交回复
热议问题