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.

Example:

Python3




import tempfile
 
temp = tempfile.TemporaryFile()
print(temp)
print(temp.name)


Output:

<_io.BufferedRandom name=7>
7

The function returns a file-like object that can be used as a temporary storage area. name attribute is used to get the random and unique name of the file. 

Note: This is not an actual visible filename and there is no reference to this file in the file system.

Creating a Named Temporary File

The NamedTemporaryFile() function creates a file in the same way as TemporaryFile() but with a visible name in the file system. It takes a delete parameter which we can set as False to prevent the file from being deleted when it is closed.

 Example:

Python3




import tempfile
 
temp = tempfile.NamedTemporaryFile()
print(temp)
print(temp.name)


Output:

<tempfile._TemporaryFileWrapper object at 0x7f77d332f6d8>
/tmp/tmprumbbjz4

This also returns a file-like object as before, the only difference is that the file has a visible name this time. 

Adding a Suffix and a Prefix to a Temporary File

We may choose to add a suffix or prefix to the name of a named temporary file, by specifying the parameters ‘suffix’ and ‘prefix’. 

Example 

Python3




import tempfile
 
temp = tempfile.NamedTemporaryFile(prefix='pre_', suffix='_suf')
print(temp.name)


Output:

/tmp/pre_ddur6hvr_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....