Python

Working with tempfile in python

Sometimes we need to store data temporarily in a file for doing any task temporarily.  For example, the monthly sales report of any organization can be generated by using storing sales data into a temporary file. It is better to store the data in a temporary file for generating the report to prevent any accidental modification of the original data. A temporary file can also be used for securing sensitive data. Creating a temporary file and doing these types of tasks can be done easily in Python by using tempfile module. This module contains many functions to create temporary files and folders, and access them easily. The uses of tempfile module in Python are shown in this article.

Creating a temporary file without tempfile module

The task of a temporary file can be done without using tempfile module by creating a simple file. For this, you have to create a normal file, do the temporary tasks and remove the file after completing the tasks. In this example, a temporary file named temp.txt is opened with write mode and a text is written in the temporary file. ‘os’ module is used here to read the content of the temp.txt file and remove the file after completing the task.

# Import os module
import os

# Define the name of the temporary file
filename = 'temp.txt'

# Open the file in reading mode
fh = open(filename, 'w')
try:

  # Print a message before writing
  print("Writing to the file>>>\n")

  # Write a string to the file
  fh.write("Testing temp file")

  # Close the file after writing
  fh.close()
finally:

  # Print a message before reading
  print("<<<Reading from the file")

  # Run bash command to read the file
  os.system("cat temp.txt")

  # Print newline
  print("\n")

# Remove the temporary file
os.remove(filename)

Output:

Run the script. The following output will appear after running the script.

Creating temporary file using TemporaryFile() method

tempfile module is used in this example to create a temporary file. This module has many methods to work with the temporary file. TemporaryFile() method is used here to create a temporary file. The temporary file is opened in the script as a text file in write mode. The temporary file will be created in the current location by default. Two lines of text is written in the temporary file by using write() method. Next, seek() method is called to set the file pointer at the starting of the file. The content of the file is printed in the terminal by using read() method. close() method of the module is used to close the file and remove the file automatically.

# Import tempfile module
import tempfile

# Declare object to open temporary file for writing
tmp = tempfile.TemporaryFile('w+t')
try:

  # Print message before writing
  print('Writing to the temporary file...')

  # Write data to temporary file
  tmp.write('Linux Hint\n')
  tmp.write('The content of temporary file')

  # Move to the starting of the file
  tmp.seek(0)

  # Read content of the temporary file
  print('Reading temporary file: \n{0}'.format(tmp.read()))
finally:

  # Remove the temporary file automatically
  tmp.close()

Output:

Run the script. The following output will appear after running the script.

Creating temporary file using NamedTemporaryFile() method

In the previous example, the name of the temporary file creates randomly. But if you want to set any custom name for the temporary file then you have to use NamedTemporaryFile() method for creating a temporary file. In this example, a temporary file is opened in write mode using NamedTemporaryFile() method. Next, the file name is set to temp.txt. One line of text is written to the file and read from the file like the previous example. It is mentioned before that the temporary file deletes automatically when close() method is called. After delete, ‘os’ module is used here to check the temporary file exists or not.

# Import tempfile module
import tempfile

# Import os module
import os

# Declare object to open temporary file for writing
tmp = tempfile.NamedTemporaryFile('w+t')

# Declare the name of the temporary file
tmp.name="temp.txt"
try:

  # Print message before writing
  print('Write data to temporary file...')

  # Write data to the temporary file
  tmp.write('This is a temporary content.')

  # Move to the starting of the file
  tmp.seek(0)

  # Read content of the temporary file
  print('Read the content of temporary file: \n{0}'.format(tmp.read()))

finally:
  # Remove the file automatically
  tmp.close()

  # Check the file exist or not
  if(os.path.exists(tmp.name)):
    print('The file exist')
  else:
    print('The file does not exist')

Output:

Run the script. The following output will appear after running the script.

Creating a temporary file with prefix and suffix

All temporary files are created in the current location for the previous examples. The location of the temporary file and, the prefix and suffix for the temporary filename can be mentioned at the time of file creation using NamedTemporaryFile() method. According to the following script, The temporary filename will start with ‘tm_’ and end with ‘_fl’. The file will store in the ‘/tmp’ folder. After creating the file, the temporary filename is printed by using ‘name’ property. Next, ‘os’ module is used to check the file is removed or not.

# Import tempfile module
import tempfile

# Import os module
import os

# Declare object to create a temporary file with suffix and prefix
tmp = tempfile.NamedTemporaryFile(mode='w+t', prefix='tm_',
suffix='_fl',
dir='/tmp')

# Print the temporary filename
print(tmp.name)
try:

  # Print message before writing
  print('Write data to temporary file...')

  # Write data to a temporary file
  tmp.write('This is a temporary content.')

finally:
  # Remove the file automatically
  tmp.close()
  if(os.path.exists(tmp.name) == False):
    print('File is removed')

Output:

Run the script. The following output will appear after running the script.

Conclusion:

It is a common requirement for any programming language to create a temporary file to do many tasks on demand and work with those data that is not required to store permanently. Some necessary methods of tempfile module are explained in this article to show the ways to use the temporary file. I, hope, the reader will be able to create and use temporary files easily after reading this article.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.