How to generate secure temporary file name using Python?


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


import tempfile
_, temp_file_path = tempfile.mkstemp()
print("File path: " + temp_file_path)

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

Published on 20-Apr-2018 10:53:00