🕯️ Magic Note
Temporary files are stored in your system’s temporary directory (like /tmp on Linux or C:\Users\Username\AppData\Local\Temp on Windows). The tempfile module handles platform specific paths automatically. When the file is closed or the program exits, the file is deleted. The memory fades. The file forgets it ever existed.
- Temporary files are automatically deleted when closed
- Use tempfile.TemporaryFile() for anonymous files (no visible name)
- Use tempfile.NamedTemporaryFile() for files with a name in the filesystem
- Use tempfile.TemporaryDirectory() for temporary folders
| Function | Description | Use When |
|---|---|---|
| TemporaryFile() | Anonymous temp file | Data that doesn’t need a name |
| NamedTemporaryFile() | Named temp file | Need to pass filename to another function |
| SpooledTemporaryFile() | Memory first, then disk | Small data that might fit in RAM |
| TemporaryDirectory() | Temporary folder | Need to store multiple files |
Python
# Creating and using a temporary file
import tempfile
with tempfile.TemporaryFile(mode=”w+”) as tmp:
tmp.write(“This is a fleeting memory”)
tmp.seek(0)
content = tmp.read()
print(content)
# Output: This is a fleeting memory
# After the with block, the file is gone
Python
# Named temporary file (visible but temporary)
import tempfile
with tempfile.NamedTemporaryFile(mode=”w+”, delete=True) as tmp:
print(f”File name: {tmp.name}”)
tmp.write(“Secret data that will vanish”)
tmp.seek(0)
print(tmp.read())
# Output: File name: /tmp/tmp12345abc
# Output: Secret data that will vanish
# After the block, the file is deleted
Python
# Temporary directory for multiple files
import tempfile
import os
with tempfile.TemporaryDirectory() as tmpdir:
file_path = os.path.join(tmpdir, “note.txt”)
with open(file_path, “w”) as f:
f.write(“Temporary note”)
print(os.listdir(tmpdir))
# Output: [‘note.txt’]
# After the block, the entire directory is deleted
- Forgetting the mode=”w+” when you need both write and read access to temporary files
- Assuming temporary files survive after the program ends, they are deleted automatically
- Not using a context manager (the with statement), risking the file not being cleaned up properly
⚡ Whisper
A heartbeat then silence. A memory then forgetfulness. The file lives for one purpose, then fades. Code that holds, then releases. No trace remains. No clutter. No ghost in the machine. Let it live. Let it go.