Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to generate random file names in Python

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. Thank you!

like image 632
zallarak Avatar asked May 08 '12 15:05

zallarak


People also ask

How do you generate random filenames in Python?

You could change 'string. ascii_letters' to any string format as you like to generate any other text, for example mobile NO, ID... Show activity on this post. In some other cases if you need the random file name to be sensible, use the faker module.

What is the best random number generator in Python?

Probably the most widely known tool for generating random data in Python is its random module, which uses the Mersenne Twister PRNG algorithm as its core generator.


2 Answers

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.

like image 79
Óscar López Avatar answered Oct 01 '22 22:10

Óscar López


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

like image 41
Levon Avatar answered Oct 01 '22 23:10

Levon