How to create a unique directory name using Python?

You can use the tempfile module to create a unique temporary directory in the most secure manner possible. There are no race conditions in the directory’s creation. The directory is readable, writable and searchable only by the creating user ID. Note that the user of mkdtemp() is responsible for deleting the temporary directory when done with it. To create a new temporary directory, use it as follows −

import tempfile
_, temp_dir_path = tempfile.mkdtemp()
# Do what you want with this directory
# And remove the directory when done

Note that you need to manually delete this directory after you're done with it.

Updated on: 18-Feb-2020


Kickstart Your Career

Get certified by completing the course

Get Started