Python Tempfile Module: A Comprehensive Tutorial With Examples

Python tempfile module supports a lot of functions that were useful for developing projects.

To discuss the functions under the tempfile module, this tutorial presents the Python tempfile module with program examples.

What is a Python Tempfile?

Python tempfile() module is a temporary file created within a program to hold information temporarily.

This method is useful as an alternative container of information while files are created or updated.

As its name suggests, the Python tempfile() is deleted as soon as you close the program.

However, this function can manage multiple users, provide temporal storage to store and move data, as well as recover data.

Additionally, the tempfile() module provides output files based on the outcome of processed data and allows users to edit or access the data in the files.

You may also want to learn how to deal with module errors, visit the link below:

Working with temporary files

templfile() is a very useful module that can secure sensitive information in your program.

The question is, how can we implement these advantageous functions in our Python program?

Let us look at the examples below.

Creating temporary files

The first example will focus on discussing how to implement the Python timeit module in creating temporary files.

We will use an example scenario where we can validate the idea of creating temporary files in our program.

Scenario: Let’s say a program requires a temporary file for use internally.

The temporary file should be created, used to hold some data, and then deleted.

We will use the Python timeit() function to help with the provided scenario.

Example Program:

import tempfile

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

Output:

<_io.BufferedRandom name=3>
3

Code Explanation

To implement the module, you first need to import a tempfile and use the tempfile.TemporaryFile() function to create a temporary file within the program.

After creating a file, the function then returns an object.

Furthermore, users may open the file through the default w+b mode and apply both read and write to it.

To show the file and its name from the program, we used the print() function.

The close() method also enables the program to delete the temporary file upon closing it.

The output displays the file as <_io.BufferedRandom name=3> and its name is 3k.

Reading and writing plain text into Temporary Files

The Python tempfile module also enables users to use temporary files for reading and writing plain text.

Now let us try using the tempfile module in reading and writing plain text into the created temporary file.

Example 1

import tempfile
  
temp = tempfile.TemporaryFile()
  
try:
    temp.write(b'Hello world!')
    temp.seek(0)
  
    print(temp.read())
finally:
    temp.close()

Output:

b'Hello world!'

Example 2

import tempfile
  
File = tempfile.TemporaryFile()
  
try:
  File.write(b'Python for Free')
  File.seek(0)
  data=File.read()
  print(data)
finally:
  File.close()

Output:

b'Python for Free'

Code Explanation:

This given example shows that the module creates a temporary file through tempfile.TemporaryFile() function where you can write data.

Now to read the written data from the temporary file, programmers will need to implement the seek() function.

This function sets the current position of the data or file into offset.

After implementing the seek() function, the users will have to go back to the beginning to find the data from the temporary file.

Then, the users may close the program to remove the temporary file.

Creating a named Temporary Files

Naming the temporary file is the simplest approach to pass it between components of the program if it includes several processes or hosts.

Furthermore, an accessible temporary file with a name is created by the NamedTemporaryFile() function.

Take a look at the examples.

Example 1:

import tempfile
  
temp = tempfile.NamedTemporaryFile()
  
print("Temporary File:", temp)
print("File Name:", temp.name)
temp.close()

Output:

Temporary File: <tempfile._TemporaryFileWrapper object at 0x7f528c570400>
File Name: /tmp/tmpsavbz29x

Example 2

import tempfile
  
myFile = tempfile.NamedTemporaryFile()
print(myFile.name)
  
myFile.close()

Output:

/tmp/tmprnjnqvt6

Code Explanation:

The example shows how to use the Python tempfile module to make a temporary file with a name.

As you can see in Examples 1 and 2, the program imports tempfile before calling the NamedTemporaryFile() function to create the file.

This function returns a file-like object for temporary storage.

NamedTemporaryFile() files will always have a name that can be seen unlike TemporaryFile files.

However, the NamedTemporaryFile() function gets deleted as soon as the user closes the program.

It also supports the deleted flags, which are set to true by default.

Providing Filename Suffix and Prefix

Another useful function of the Python tempfile module is the method of adding prefix or suffix to the temporary file.

This function allows programmers to easily distinguish the temporary file made by the program from their permanent files.

Here are the example demonstrations of implementing tempfile prefix and suffix:

Example 1:

import tempfile
  
a = tempfile.NamedTemporaryFile(prefix="demoPrefix_",
                                   suffix="_demoSuffix")
  
print("File:", a)
print("File Name:", a.name)
a.close()

Output:

File: <tempfile._TemporaryFileWrapper object at 0x7f037b7e2400>
File Name: /tmp/demoPrefix_4to81odv_demoSuffix

Example 2:

import tempfile
  
temp=tempfile.NamedTemporaryFile(prefix='Python_',
                                 suffix='_for_Free')
print(temp.name)

Output:

/tmp/Python_xrqbgqqp_for_Free

Code Explanation:

The example shows that it is possible to apply a prefix and a suffix to the named temporary file.

In Examples 1 and 2, the NamedTemporaryFile() function uses the prefix and suffix parameters of the Python tempfile module.

As you saw in the previous examples, all you need to do to call this function is add two parameters: a suffix and a prefix.

If the module then sends suffix and prefix to the NamedTemporaryFile() function, those arguments will automatically be added to the beginning (prefix) and end (suffix) of the file name.

mkstemp()

The mkstemp() function is like the TemporaryFile() function that also generates a temporary file.

Additionally, the suffix and prefix parameters can be added to each newly formed temporary file.

In contrast to TemporaryFile(), however, the created file is not automatically deleted.

Therefore, this function must be manually deactivated.

Let us try its implementation through the example below.

Example:

import tempfile
  
File = tempfile.mkstemp(suffix = '_PFF')
print(File)

Output:

(3, '/tmp/tmpanbuzr7l_PFF')

mkdtemp()

The mkstemp() function of the Python tempfile module creates a temporary directory in the temp folder of the operating system and returns its absolute path.

Moreover, you may utilize the dir argument to define the creation location manually.

Remember that once this folder is used, it should also be removed manually.

Example Program:

import tempfile
  
File = tempfile.mkdtemp(dir = "c:/python3")
print(File)

Output:

c:/python36\tmpruxmm66u

gettempdir()

The gettempdir() function, on the other hand, returns the name of the directory to store temporary files.

This function is also under the Python tempfile module.

Additionally, the directory’s name is generally obtained from the tempdir environment variable.

On Windows, it’s usually user/AppData/Local/Temp, windowsdir/temp, or systemdrive/temp, but on Linux, it’s usually just /tmp.

Nevertheless, these directories were used as the default value of the dir parameter.

Example Program:

import tempfile
  
File = tempfile.gettempdir()
print(File)

Output:

/tmp

What is Tempfile used for?

The Python tempfile module is used for the temporary storage of data (information) within a project while creating or modifying the actual file.

This module covers different functions to help programmers have a temporary container for their important files.

Moreover, though the tempfile module is only temporal, it still enables programmers to recover their data and manage their sensitive information.

This service will be available as long as you haven’t closed the program.

Summary

In summary, the Python tempfile module covered the important discussions as well as its included functions.

The tutorial about this tempfile module clarifies that it is one of Python’s built-in modules that supports multiple functions.

This topic has emphasized that the purpose of the tempfile module is to create short-term storage for important data in a program.

Leave a Comment