Open In App

Python tempfile module

Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done. In this case, a problem arose that many output files were created and this cluttered the file system with unwanted files that would require deleting every time the program ran.

In this situation, tempfiles are used to create temporary files so that next time we don’t have to find delete when our program is done with them



Working with temporary files

A temporary file can also be used for securing sensitive data. This module contains many functions to create temporary files and folders, and access them easily.

Creating Temporary Files

Suppose your application needs a temporary file for use within the program, i.e. it will create one file, use it to store some data, and then delete it after use. To achieve this, we can use the TemporaryFile() function.



Code:




import tempfile
  
temp = tempfile.TemporaryFile()
print('temp:',temp)
print('temp.name:', temp.name)
temp.close()

Output:

temp: <_io.BufferedRandom name=6>
temp.name: 6

Reading and writing plain text into Temporary Files

Similar to reading or writing from a file, we can use the same kind of function calls to do this from a temporary file too!!

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
  
f = tempfile.TemporaryFile()
  
try:
  f.write(b'Welcome to geeksforgeeks')
  f.seek(0)
  data=f.read()
  print(data)
finally:
  f.close()

Output:

b'Welcome to geeksforgeeks'

Creating a named Temporary Files 

If your application spans multiple processes, or even hosts, naming the file is the simplest way to pass it between parts of the application. The NamedTemporaryFile() function creates a file with a name, accessed from the name attribute.

Example 1:




import tempfile
  
print("Creating a named temporary file..")
temp = tempfile.NamedTemporaryFile()
  
print("Created file is:", temp)
print("Name of the file is:", temp.name)
temp.close()

Output:

Creating a named temporary file..
Created file is: <tempfile._TemporaryFileWrapper object at 0x7ff135ed1710>
Name of the file is: /tmp/tmpg8efl258

Example 2:




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

Output:

/tmp/tmp6nxmoagy

Providing Filename Suffix and Prefix

Sometimes we need to add a prefix or suffix to a temp-file’s name. It will help us to identify all temp files created by our program

Example 1:




import tempfile
  
temp = tempfile.NamedTemporaryFile(prefix="demoPrefix_",
                                   suffix="_demoSuffix")
  
print("Created file is:", temp)
print("Name of the file is:", temp.name)
temp.close()

Output:

Created file is: <tempfile._TemporaryFileWrapper object at 0x7fbf5d39b6d8>
Name of the file is: /tmp/demoPrefix_t_inxb7v_demoSuffix

Example 2:




import tempfile
  
temp=tempfile.NamedTemporaryFile(suffix='_greeks',
                                 prefix='forgreeks_')
print(temp.name)

Output:

/tmp/forgreeks_4sigabye_greeks

Article Tags :