[Tutor] randomness

Tim Peters tutor@python.org
Sat, 16 Jun 2001 03:44:08 -0400


[Andrew Wilkins]
> What's a good way to generate a random unique file name? ...

The bad news is that it's surprisingly difficult to do this "correctly"
across platforms.  The good news is that's why Python does it for you:  look
in the Library Reference Manual for the standard tempfile.py module.

tempfile.TemporaryFile() is the best function to use from that, because it
returns an open file object as secure as possible against attacks.

tempfile.mktemp() can be used to get just a path name that didn't exist at
the time you called mktemp(), but it's impossible then to guarantee that
some other process won't create a file with that name before you get around
to doing so.  Python plays several tricks under the covers to make it
exceedingly unlikely that another process will do so, but "guarantee" is a
promise it can't make.

Note that tempfile.py works fine on all platforms (whether Unix, Windows or
Mac).