Temporary Files & Directories

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.

Learn Temporary Files & Directories in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.

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

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:

NamedTemporaryFile additionally gives you a real path via .name , so other code can open it while it's alive:

2 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:

The variable d is the path to the new directory. Pairing it with pathlib.Path makes building child paths clean and cross-platform.

3 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:

🎯 Your Turn: Fill in the Blanks

Replace each ___ so a temp directory holds a file of numbers, which you read back and sum.

⚠️ Common Errors

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.

📚 Keep Learning

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.

🚀 Up next: glob & fnmatch — find files by pattern across folders.

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