Best way to generate random file names in Python

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

    Python has facilities to generate temporary file names, see http://docs.python.org/library/tempfile.html. For instance:

    In [4]: import tempfile
    

    Each call to tempfile.NamedTemporaryFile() results in a different temp file, and its name can be accessed with the .name attribute, e.g.:

    In [5]: tf = tempfile.NamedTemporaryFile()
    In [6]: tf.name
    Out[6]: 'c:\\blabla\\locals~1\\temp\\tmptecp3i'
    
    In [7]: tf = tempfile.NamedTemporaryFile()
    In [8]: tf.name
    Out[8]: 'c:\\blabla\\locals~1\\temp\\tmpr8vvme'
    

    Once you have the unique filename it can be used like any regular file. Note: By default the file will be deleted when it is closed. However, if the delete parameter is False, the file is not automatically deleted.

    Full parameter set:

    tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
    

    it is also possible to specify the prefix for the temporary file (as one of the various parameters that can be supplied during the file creation):

    In [9]: tf = tempfile.NamedTemporaryFile(prefix="zz")
    In [10]: tf.name
    Out[10]: 'c:\\blabla\\locals~1\\temp\\zzrc3pzk'
    

    Additional examples for working with temporary files can be found here

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

    If you need no the file path, but only the random string having predefined length you can use something like this.

    >>> import random
    >>> import string
    
    >>> file_name = ''.join(random.choice(string.ascii_lowercase) for i in range(16))
    >>> file_name
    'ytrvmyhkaxlfaugx'
    
    0 讨论(0)
  • 2020-12-04 09:16

    You could use the UUID module for generating a random string:

    import uuid
    filename = str(uuid.uuid4())
    

    This is a valid choice, given that an UUID generator is extremely unlikely to produce a duplicate identifier (a file name, in this case):

    Only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs.

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

    I personally prefer to have my text to not be only random/unique but beautiful as well, that's why I like the hashids lib, which generates nice looking random text from integers. Can installed through

    pip install hashids

    Snippet:

    import hashids
    hashids = hashids.Hashids(salt="this is my salt", )
    print hashids.encode(1, 2, 3)
    >>> laHquq
    

    Short Description:

    Hashids is a small open-source library that generates short, unique, non-sequential ids from numbers.

    0 讨论(0)
  • 2020-12-04 09:20
    import uuid
       imageName = '{}{:-%Y%m%d%H%M%S}.jpeg'.format(str(uuid.uuid4().hex), datetime.now())
    
    0 讨论(0)
  • 2020-12-04 09:22

    a common approach is to add a timestamp as a prefix/suffix to the filename to have some temporal relation to the file. If you need more uniqueness you can still add a random string to this.

    import datetime
    basename = "mylogfile"
    suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
    filename = "_".join([basename, suffix]) # e.g. 'mylogfile_120508_171442'
    
    0 讨论(0)
提交回复
热议问题