Asked By – zallarak
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!
Now we will see solution for issue: Best way to generate random file names in Python
Python has facilities to generate temporary file names, see http://docs.python.org/library/tempfile.html. For instance:
In : 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 : tf = tempfile.NamedTemporaryFile() In : tf.name Out: 'c:\\blabla\\locals~1\\temp\\tmptecp3i' In : tf = tempfile.NamedTemporaryFile() In : tf.name Out: '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
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 : tf = tempfile.NamedTemporaryFile(prefix="zz") In : tf.name Out: 'c:\\blabla\\locals~1\\temp\\zzrc3pzk'
Additional examples for working with temporary files can be found here
This question is answered By – Levon
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0