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:

Similar Reads

Creating a Temporary File

The file is created using the TemporaryFile() function of the tempfile module. By default, the file is opened in w+b mode, that is, we can both read and write to the open file. Binary mode is used so that files can work with all types of data. This file may not have a proper visible name in the file system....

Reading and Writing to a Temporary File

...

Creating a Temporary Directory

...

Secure Temporary File and Directory

...

Location of Temporary Files

The write() method is used to write to a temporary file. It takes input as binary data by default. We can pass the string to be written as input, preceded by a ‘b’ to convert it to binary data....