Skip to main content

How to Create a Temporary Folder in Python with tempfile

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Some files are only needed for a moment: a report you upload somewhere, or a file another library insists on reading from disk. tempfile.TemporaryDirectory, from Python's standard library, gives you a fresh, empty folder and deletes it, with everything inside, when you're done. This guide writes a file into one and checks that the folder is gone afterwards, with real output from Python 3.15.2.

Syntax​

Syntax
import tempfile

with tempfile.TemporaryDirectory() as <folder>:
<work with files inside folder>
# here the folder and everything in it are deleted
PartWhat it means
tempfile.TemporaryDirectory()"Securely creates a temporary directory", in Python's words: a new folder with a random name, in your system's folder for temporary files
with ... as <folder>Uses it as a context manager: <folder> is the new folder's path, as a string
The end of the with block"The newly created temporary directory and all its contents are removed from the filesystem"

TemporaryDirectory() also takes optional arguments: prefix and suffix for the folder's name, dir for where to create it, and delete=False to keep it after the block.

Step 1: Write a File into a Temporary Folder​

The example writes a one-line report into a temporary folder, lists what the folder holds, then checks whether the folder still exists after the with block. Create temp_folder.py:

The temp_folder.py script in a macOS-style code window: a with block over tempfile.TemporaryDirectory() that prints the folder's path, writes report.txt into it with pathlib, and lists the folder's contents, then a line after the block that prints whether the folder still exists.

temp_folder.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as folder:
print("Working in:", folder)
report = Path(folder) / "report.txt"
report.write_text("Temporary results\n")
print("Inside it:", [path.name for path in Path(folder).iterdir()])

print("Still there afterwards?", Path(folder).exists())
LineWhat it does
with tempfile.TemporaryDirectory() as folder:Creates the folder and puts its path in folder
Path(folder) / "report.txt"Builds the path of a file inside it. How to Build File Paths in Python with pathlib explains the /
report.write_text(...)Creates the file and writes one line into it
Path(folder).iterdir()Lists what the folder holds
The last lineRuns after the block has ended, and checks whether the folder still exists

Step 2: Run It​

Terminal
uv run python temp_folder.py
Output
Working in: /var/folders/…/T/tmpqfmdqebu
Inside it: ['report.txt']
Still there afterwards? False

A terminal running uv run python temp_folder.py: it prints the temporary folder's path under /var/folders ending in T/tmpqfmdqebu, the folder's contents, a list holding report.txt, and Still there afterwards? False.

  • Working in: shows where Python created the folder. On a Mac it's under /var/folders, in a folder of random characters that belongs to your user account; I shortened that part to …. The last part, tmpqfmdqebu, is the folder's own random name, and yours will differ.
  • Inside it: shows that report.txt was written there.
  • Still there afterwards? False: the folder and the file in it were deleted when the with block ended.

Where the Folder Is Created​

Python picks the location in this order: the folder named by the TMPDIR, TEMP or TMP environment variable, whichever is set first, and otherwise a fixed list for your system:

SystemWhere the temporary folder usually is
macOS/var/folders/…/T/, which macOS sets in TMPDIR
Windows%USERPROFILE%\AppData\Local\Temp
Linux/tmp

tempfile.gettempdir() returns the one Python uses on your computer.

Common Mistakes​

MistakeWhat happensDo this instead
Using the folder after the with blockFileNotFoundError: [Errno 2] No such file or directory, because the folder is already goneDo everything that needs the files inside the block
Returning the folder's path from a functionThe caller gets a path to a folder that no longer existsDo the work inside the function, or pass the files' contents back instead
Keeping a file open when the block ends, on WindowsCleanup fails with a PermissionErrorClose every file before the block ends, for example by opening them with with too

Troubleshooting​

SymptomLikely causeFix
The folder isn't deletedIt was created with delete=FalseRemove delete=False, or call the object's cleanup() yourself
Temporary files fill up a small diskTMPDIR points to a small drivePoint TMPDIR at a larger drive, or pass dir= to TemporaryDirectory()

FAQ​

Can I choose part of the folder's name?​

Yes: tempfile.TemporaryDirectory(prefix="report-") creates a folder whose name starts with report-, followed by random characters.

Is the folder deleted if my code fails inside the block?​

Yes. Leaving a with block because of an error still runs the cleanup, so the folder is removed either way.

Can other users read the folder?​

Python creates it "securely using the same rules as mkdtemp()", which the documentation describes as "readable, writable, and searchable only by the creating user ID".

Conclusion​

with tempfile.TemporaryDirectory() as folder: created a fresh folder under /var/folders on a Mac, report.txt was written into it, and the folder was gone as soon as the block ended. Put everything that needs the files inside the block, and Python cleans up after you.

Additional Resources​