Python: How to create a unique file name? Python: How to create a unique file name? python python

Python: How to create a unique file name?


I didn't think your question was very clear, but if all you need is a unique file name...

import uuidunique_filename = str(uuid.uuid4())


If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocessimport tempfileimport os(fd, filename) = tempfile.mkstemp()try:    tfile = os.fdopen(fd, "w")    tfile.write("Hello, world!\n")    tfile.close()    subprocess.Popen(["/bin/cat", filename]).wait()        finally:    os.remove(filename)

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)


The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as random filename because it will return a hex string without dashes.

import uuidfilename = uuid.uuid4().hex

The outputs should like this:

>>> import uuid>>> uuid.uuid()UUID('20818854-3564-415c-9edc-9262fbb54c82')>>> str(uuid.uuid4())'f705a69a-8e98-442b-bd2e-9de010132dc4'>>> uuid.uuid4().hex'5ad02dfb08a04d889e3aa9545985e304'  # <-- this one