Secure Temporary File and Directory
We can securely create a temporary file using mkstemp(). The file created by this method is readable and writable only by the creating user. We can add prefix and suffix parameters like in NamedTemporaryFile(). The default mode is binary, but we can open it in text mode by setting the ‘text’ parameter as True. This file does not get deleted when closed.
Example:
Python3
import tempfile secure_temp = tempfile.mkstemp(prefix = "pre_" ,suffix = "_suf" ) print (secure_temp) |
Output:
(71, '/tmp/pre_i5us4u9j_suf')
Similarly, we can create a secure temporary directory using mkdtemp() method.
Example:
Python3
import tempfile secure_temp_dir = tempfile.mkdtemp(prefix = "pre_" ,suffix = "_suf" ) print (secure_temp_dir) |
Output:
/tmp/pre_9xmtwh4u_suf
Create temporary files and directories using tempfile
Python tempfile module allows you to create a temporary file and perform various operations on it. Temporary files may be required when we need to store data temporarily during the program’s execution or when we are working with a large amount of data. These files are created with unique names and stored in a platform-dependent default location. The files created using tempfile module are deleted as soon as they are closed.
In this tutorial, we will cover how to create and edit temporary files: