Best way to generate random file names in Python

前端 未结 11 2079
囚心锁ツ
囚心锁ツ 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:28

    You could use the random package:

    import random
    file = random.random()
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-04 09:31
    >>> import random
    >>> import string    
    >>> alias = ''.join(random.choice(string.ascii_letters) for _ in range(16))
    >>> alias
    'WrVkPmjeSOgTmCRG'
    

    You could change 'string.ascii_letters' to any string format as you like to generate any other text, for example mobile NO, ID...

    0 讨论(0)
  • 2020-12-04 09:33

    The OP requested to create random filenames not random files. Times and UUIDs can collide. If you are working on a single machine (not a shared filesystem) and your process/thread will not stomp on itselfk, use os.getpid() to get your own PID and use this as an element of a unique filename. Other processes would obviously not get the same PID. If you are multithreaded, get the thread id. If you have other aspects of your code in which a single thread or process could generate multiple different tempfiles, you might need to use another technique. A rolling index can work (if you aren't keeping them so long or using so many files you would worry about rollover). Keeping a global hash/index to "active" files would suffice in that case.

    So sorry for the longwinded explanation, but it does depend on your exact usage.

    0 讨论(0)
  • 2020-12-04 09:39

    Adding my two cents here:

    In [19]: tempfile.mkstemp('.png', 'bingo', '/tmp')[1]
    Out[19]: '/tmp/bingoy6s3_k.png'
    

    According to the python doc for tempfile.mkstemp, it creates a temporary file in the most secure manner possible. Please note that the file will exist after this call:

    In [20]: os.path.exists(tempfile.mkstemp('.png', 'bingo', '/tmp')[1])
    Out[20]: True
    
    0 讨论(0)
提交回复
热议问题