tempfile

The Python tempfile module provides a simple way to create temporary files and directories. This module is particularly useful when you need to store data temporarily during program execution, ensuring that the data is automatically cleaned up when no longer needed.

Here’s a quick example:

Python
>>> import tempfile

>>> with tempfile.TemporaryFile() as temp:
...     temp.write(b"Hello, World!")
...     temp.seek(0)
...     temp.read()
...
b"Hello, World!"

Key Features

  • Creates temporary files and directories
  • Automatically cleans up temporary resources
  • Provides secure handling of temporary files
  • Supports both named and unnamed temporary files
  • Cross-platform compatibility (Windows, macOS, Linux)

Frequently Used Classes and Functions

Object Type Description
tempfile.TemporaryFile Function Creates a temporary file
tempfile.NamedTemporaryFile Function Creates a named temporary file
tempfile.TemporaryDirectory Function Creates a temporary directory
tempfile.mkstemp() Function Provides a low-level function to create a temporary file
tempfile.mkdtemp() Function Provides a low-level function to create a temporary directory
tempfile.gettempdir() Function Returns the default directory for temporary files
tempfile.gettempprefix() Function Returns the default prefix for temporary file names

Examples

Create a named temporary file:

Python
>>> with tempfile.NamedTemporaryFile(delete=False) as temp:
...     print(temp.name)
...
'/tmp/tmpabcd1234'

Create a temporary directory:

Python
>>> with tempfile.TemporaryDirectory() as temp_dir:
...     print(temp_dir)
...
'/tmp/tmpabcd5678'

Common Use Cases

  • Creating temporary files for intermediate data storage
  • Managing temporary directories for temporary data processing
  • Testing file and directory operations in a safe, isolated environment
  • Generating unique file paths for temporary use
  • Sharing temporary files between processes or subprocesses
  • Replacing insecure or hard-coded temporary paths in code

Real-World Example

Suppose you need to extract the content of a tar file to a temporary directory, check for .txt files, and create a backup archive containing only those files:

Python
>>> import tempfile, tarfile, pathlib, os

>>> def backup_txt_files(archive_path, backup_name="text_backup.tar.gz"):
...     with tempfile.TemporaryDirectory() as temp_dir:
...         temp_dir_path = pathlib.Path(temp_dir)
...
...         with tarfile.open(archive_path, mode="r:*") as tar:
...             tar.extractall(path=temp_dir)
...
...         txt_files = list(temp_dir_path.glob("*.txt"))
...         if not txt_files:
...             print("No .txt files found to back up.")
...             return
...
...         with tarfile.open(backup_name, mode="w:gz") as backup_tar:
...             for txt_file in txt_files:
...                 backup_tar.add(txt_file, arcname=txt_file.name)
...                 print(f"Backed up: {txt_file.name}")
...         print(f"Created backup archive: {backup_name}")
...

>>> backup_txt_files("sample.tar.gz")
Backed up: report.txt
Backed up: notes.txt
Created backup archive: text_backup.tar.gz

In this example, a tar archive is extracted to a temporary directory. All .txt files found in the extracted content are packed into a new backup archive named text_backup.tar.gz in the current directory. The temporary directory and its contents are automatically cleaned up after the context manager exits.

Tutorial

How to Get a List of All Files in a Directory With Python

In this tutorial, you'll be examining a couple of methods to get a list of files and folders in a directory with Python. You'll also use both methods to recursively list directory contents. Finally, you'll examine a situation that pits one method against the other.

intermediate

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 24, 2025