Temporary Files & Directories
Reviewed & published by Brayan K
The tempfile module creates files and directories in a safe, unique, platform-correct location for short-lived scratch data — and the high-level helpers clean themselves up automatically.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Whenever you need a place to stash intermediate data, generate a report before moving it, or test file-handling code, tempfile is the right and safe choice — never a hardcoded path.
What You'll Learn in This Lesson
- Scratch files with TemporaryFile
- Files with a real path via NamedTemporaryFile
- Self-cleaning folders with TemporaryDirectory
- Manual control with mkstemp and mkdtemp
- Why with-blocks guarantee cleanup
- Why you should never hardcode /tmp
1 TemporaryFile and NamedTemporaryFile
TemporaryFile gives you a scratch file you read and write through the file object — it vanishes when closed. Open it in "w+" mode to write then seek(0) and read back:
import tempfile
with tempfile.TemporaryFile(mode="w+") as f:
f.write("scratch data")
f.seek(0) # rewind to the start
print("Read back:", f.read())
print("File auto-deleted after the with block")NamedTemporaryFile additionally gives you a real path via .name, so other code can open it while it's alive:
import tempfile
import os
with tempfile.NamedTemporaryFile(mode="w+", suffix=".txt") as f:
f.write("line1\nline2\n")
f.flush()
print("Has a real path:", os.path.basename(f.name).endswith(".txt"))
f.seek(0)
print("Lines:", len(f.readlines()))import tempfile
with tempfile.TemporaryFile(mode="w+") as f:
f.write("scratch data")
f.seek(0)
print("Read back:", f.read())
print("File auto-deleted after the with block")
# Expected output:
# Read back: scratch data
# File auto-deleted after the with block2 TemporaryDirectory: A Self-Cleaning Folder
TemporaryDirectory creates a whole folder you can fill with files. The instant the with block ends, the directory and everything inside it is deleted — perfect for tests and multi-file scratch work:
import tempfile
import os
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "notes.txt"
p.write_text("hello temp dir")
print("Exists inside block:", p.exists())
print("Content:", p.read_text())
saved = d
print("Dir removed after block:", not os.path.exists(saved))The variable d is the path to the new directory. Pairing it with pathlib.Path makes building child paths clean and cross-platform.
import tempfile
import os
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "notes.txt"
p.write_text("hello temp dir")
print("Exists inside block:", p.exists())
print("Content:", p.read_text())
saved = d
print("Dir removed after block:", not os.path.exists(saved))
# Expected output:
# Exists inside block: True
# Content: hello temp dir
# Dir removed after block: True3 mkstemp: Manual Control (You Clean Up)
When you need a temp file that outlives a single block, use mkstemp(). It returns a low-level file descriptor and a path — but does not auto-delete. You must remove it yourself, ideally in a finally so cleanup always runs:
import tempfile
import os
fd, path = tempfile.mkstemp(suffix=".dat")
try:
with os.fdopen(fd, "w") as f: # wrap the descriptor
f.write("manual cleanup needed")
print("Created:", path.endswith(".dat"))
print("Size:", os.path.getsize(path), "bytes")
finally:
os.remove(path) # YOU must delete it
print("Cleaned up:", not os.path.exists(path))import tempfile
import os
fd, path = tempfile.mkstemp(suffix=".dat")
try:
with os.fdopen(fd, "w") as f:
f.write("manual cleanup needed")
print("Created:", path.endswith(".dat"))
print("Size:", os.path.getsize(path), "bytes")
finally:
os.remove(path)
print("Cleaned up:", not os.path.exists(path))
# Expected output:
# Created: True
# Size: 21 bytes
# Cleaned up: True🎯 Your Turn: Fill in the Blanks
Replace each ___ so a temp directory holds a file of numbers, which you read back and sum.
import tempfile
from pathlib import Path
with tempfile.___() as d: # hint: a self-cleaning folder
f = Path(d) / "data.txt"
f.write_text("42\n99\n7\n")
numbers = [int(x) for x in f.read_text().split()]
print("Sum:", ___(numbers)) # hint: total of a list
# Expected output:
# Sum: 148⚠️ Common Errors
❌ Hardcoding a temp path
f = open("/tmp/scratch.txt", "w") # breaks on Windows, may clashwith tempfile.NamedTemporaryFile(mode="w") as f:
...f.write("data")
print(f.read()) # empty! cursor is at the end✅ Seek back to the start
f.write("data")
f.seek(0)
print(f.read()) # 'data'❌ Forgetting to delete an mkstemp file
mkstemp does not clean up. Without an os.remove(path) (ideally in finally), you leak files into the temp directory. Use the with-based helpers unless you truly need manual control.
🎯 Mini Challenge: Build & Total Reports
In a temporary directory, write three report files each holding a value=... line, then glob them back, extract the numbers, and print the grand total. The folder cleans itself up.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
base = Path(d)
for i in range(1, 4):
(base / f"report_{i}.txt").write_text(f"value={i * 100}")
files = sorted(base.glob("*.txt"))
print("Created", len(files), "files")
total = sum(int(p.read_text().split("=")[1]) for p in files)
print("Total value:", total)
print("All cleaned up automatically")
# Expected output:
# Created 3 files
# Total value: 600
# All cleaned up automatically📚 Keep Learning
- • tempfile — Generate temporary files and directories
- • pathlib — Object-oriented filesystem paths
- • os.fdopen — Wrap a file descriptor
Frequently Asked Questions
Lesson complete — you handle temp data safely!
You can create scratch files with TemporaryFile, named files with a real path via NamedTemporaryFile, self-cleaning folders with TemporaryDirectory, and take manual control with mkstemp/mkdtemp — and you'll never hardcode /tmp again.
Practice quiz
Why should you avoid hardcoding a path like /tmp/myfile.txt?
- It's slower than tempfile
- Python forbids absolute paths
- It isn't portable, can clash, and predictable names are a security risk
- It only works on Windows
Answer: It isn't portable, can clash, and predictable names are a security risk. The temp dir differs by OS, fixed names can collide, and predictable temp names are a classic security hole.
What is the difference between TemporaryFile and NamedTemporaryFile?
- NamedTemporaryFile guarantees a real path via .name; TemporaryFile may not
- TemporaryFile is faster
- NamedTemporaryFile never auto-deletes
- They are identical
Answer: NamedTemporaryFile guarantees a real path via .name; TemporaryFile may not. NamedTemporaryFile guarantees a filesystem path (.name) other code can open; TemporaryFile may have no visible name.
When does a TemporaryDirectory delete itself and its contents?
- Never — you must delete it manually
- After 60 seconds
- When the program crashes only
- When the with-block exits
Answer: When the with-block exits. TemporaryDirectory removes the folder and everything inside it the instant its with-block ends.
Which functions do NOT auto-clean up after themselves?
- TemporaryFile and TemporaryDirectory
- mkstemp and mkdtemp
- NamedTemporaryFile and TemporaryFile
- All tempfile functions auto-clean
Answer: mkstemp and mkdtemp. mkstemp and mkdtemp hand you a path but do NOT auto-delete; you must remove them yourself, ideally in finally.
After writing to a TemporaryFile, what must you do before reading it back?
- Call f.seek(0) to rewind to the start
- Close and reopen it
- Call f.reset()
- Nothing — read works immediately
Answer: Call f.seek(0) to rewind to the start. The cursor sits after your last write, so seek(0) rewinds to the start before reading, or you'll get nothing.
What does tempfile.mkstemp() return?
- A file object
- Just a path string
- A file descriptor and a path
- A TemporaryDirectory
Answer: A file descriptor and a path. mkstemp returns a low-level (fd, path) pair; you wrap the descriptor (e.g. with os.fdopen) and clean up the path yourself.
Which mode lets you write to a TemporaryFile and then read it back?
- "r"
- "w+"
- "w"
- "a"
Answer: "w+". Open in "w+" so you can write, seek(0), and read the data back through the same file object.
Why prefer the with-based helpers over mkstemp/mkdtemp when possible?
- They are faster
- They produce shorter paths
- They work without importing tempfile
- They can't leak — cleanup is guaranteed even on exceptions
Answer: They can't leak — cleanup is guaranteed even on exceptions. with-based helpers clean up automatically even if an exception is raised, so they can't leak temp files.
What is the best way to ensure an mkstemp file is removed?
- Hope the OS deletes it
- Call os.remove(path), ideally in a finally block
- Set the file to read-only
- Rename it
Answer: Call os.remove(path), ideally in a finally block. mkstemp does not clean up, so delete it yourself with os.remove(path) inside a finally so cleanup always runs.
When is mkstemp/mkdtemp the right choice over the with-based helpers?
- Always — they are the modern API
- When you want automatic cleanup
- When the temp file or directory must outlive a single with-block
- Only on Windows
Answer: When the temp file or directory must outlive a single with-block. Reach for mkstemp/mkdtemp when you need to manage the lifetime yourself, beyond a single with-block.
Continue this course
- Previous: contextlib: contextmanager, suppress, ExitStack
- Next: Finding Files with glob & fnmatch — Match file paths with wildcards using glob and fnmatch
- Quick reference: Python cheat sheet
Frequently asked questions
Why not just hardcode a path like /tmp/myfile.txt?
Hardcoding paths is fragile and unsafe. The temp directory differs across operating systems (it isn't /tmp on Windows). A fixed name can clash with another program or another run of yours, and predictable temp names are a classic security hole. tempfile picks a safe, unique location for you and works on every platform.
What's the difference between TemporaryFile and NamedTemporaryFile?
TemporaryFile may not have a visible filesystem name and is ideal for pure scratch data you only access through the file object. NamedTemporaryFile guarantees a real path (its .name attribute) that other code or processes can open while it's alive. Use Named when something else needs to find the file by path.
Do temporary files clean themselves up?
The objects used with 'with' do. TemporaryFile, NamedTemporaryFile, and TemporaryDirectory all delete themselves when the with-block exits — even if an exception is raised. The lower-level mkstemp() and mkdtemp() do NOT auto-clean; they hand you a path and you're responsible for removing it yourself.
When should I use mkstemp/mkdtemp instead?
Use them when you need a temp file or directory whose lifetime extends beyond a single with-block — for example, a file you create now and hand off to another part of the program to delete later. They give you full manual control, at the cost of having to clean up yourself, usually inside a try/finally.