Create temporary files and directories using tempfile
Last Updated :
18 Jan, 2024
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:
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
Reading and Writing to a Temporary File
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.
The write function returns the number of characters written. If we open the file in text mode(w+t), we can use the writelines() method instead, which takes a string parameter. After writing to the file, the pointer is at the end of the file. So, before we can read the contents, seek() method is called to set the file pointer at the start of the file.
seek() takes as argument the index of the character before which we want to place the pointer. The read() function is then used to read the contents.
Example:
Python3
import tempfile
temp = tempfile.TemporaryFile()
temp.write(b'foo bar')
temp.seek(0)
print(temp.read())
temp.close()
Output :
b'foo bar'
Creating a Temporary Directory
Like creating files, we can also create a temporary directory to store our temporary files. The TemporaryDirectory() function is used to create the directory. After we are done working with the temporary files, the directory needs to be deleted manually using os.removedirs().
Example:
Python3
import tempfile
import os
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir)
Output:
<TemporaryDirectory '/tmp/tmpgjl5ki_5'>
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
Location of Temporary Files
We can set the location where the files are stored by setting the tempdir attribute. The location can be fetched using gettempdir() method. When we create a temporary file or directory, Python searches in a standard list of directories to find one in which the calling user can create files.
The list in order of preference is :
- The directory named by the TMPDIR environment variable.
- The directory named by the TEMP environment variable.
- The directory named by the TMP environment variable.
- A platform-specific directory:
- On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
- On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
- The current working directory.
Example:
Python3
import tempfile
tempfile.tempdir = "/temp"
print(tempfile.gettempdir())
Output:
/temp
We have covered the methods used to create temporary files and directories. We have also covered different operations like creating named temporary files, adding prefixes and suffixes, and setting the location of the temporary files.
Temporary files are a very important concept in Advanced Python programming. Creating and using temporary files will help you in many operations like handling intermediate data, testing, development, etc.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read