Site Tools


import-tempfile

import tempfile

import tempfile is a Python import that creates temporary files and directories. Use it for safe temporary storage that's automatically cleaned up.

Example

# Python
# description: create temporary files and directories
 
import tempfile
import os
 
# Temporary file (deleted when closed)
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
    f.write("temporary data")
    temp_path = f.name
 
print(f"Temp file: {temp_path}")
os.remove(temp_path)
 
# Temporary directory
with tempfile.TemporaryDirectory() as tmpdir:
    temp_file = os.path.join(tmpdir, "data.txt")
    with open(temp_file, "w") as f:
        f.write("temporary data")
    print(f"Files in temp dir: {os.listdir(tmpdir)}")
# tmpdir automatically deleted
 
# Temporary directory that persists
tmpdir = tempfile.mkdtemp()
print(f"Temp dir: {tmpdir}")
# Note: you must clean it up manually

Common functions and classes

  • tempfile.NamedTemporaryFile(): temporary named file
  • tempfile.TemporaryDirectory(): temporary directory (auto-cleanup)
  • tempfile.mkdtemp(): create temporary directory
  • tempfile.mkstemp(): create temporary file (returns fd, path)
  • delete=False: keep temp file after closing
import-tempfile.md · Last modified: by 127.0.0.1