Python Reference ยท Files, Paths and Text I/O
The tempfile module
Reference for Python's tempfile module: TemporaryFile, NamedTemporaryFile, TemporaryDirectory, mkstemp, gettempdir and automatic cleanup.
tempfile creates temporary files and folders safely. It picks a unique name in the system's temporary folder, creates the file so nobody else can claim the name first, and, with the right function, deletes it automatically when you are finished.
Use it for scratch data: a download to verify before saving, a file to hand to a program that wants a path, or a throwaway folder in a test. Always prefer it to inventing names like /tmp/myapp.tmp, which collide and can be hijacked.
import tempfile with tempfile.TemporaryDirectory() as folder: print("working in a folder that will vanish")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
tempfile.TemporaryFile(mode="w+b", suffix=None, prefix=None, dir=None, encoding=None) tempfile.NamedTemporaryFile(mode="w+b", suffix=None, prefix=None, dir=None, delete=True) tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None) tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) tempfile.mkdtemp(suffix=None, prefix=None, dir=None) tempfile.gettempdir()
| Name | Description |
|---|---|
mode |
File mode as in open(). The default is binary read-write ("w+b"); use "w+" for text. |
suffix, prefix |
Text added to the end or start of the generated name, such as ".csv". |
dir |
Create inside this folder instead of the system temporary folder. |
delete |
NamedTemporaryFile only: remove the file on close (default True). Python 3.12 adds delete_on_close. |
encoding, newline |
Same meaning as in open(), for text mode. |
Return value: TemporaryFile, NamedTemporaryFile and SpooledTemporaryFile return file-like objects (use them in with). TemporaryDirectory returns an object whose with ... as name value is the folder path. mkstemp() returns (file_descriptor, path), mkdtemp() a path, gettempdir() a string.
Raises: FileExistsError if a unique name cannot be found, FileNotFoundError if dir does not exist, PermissionError.
Usage notes
- Use
with. Files and folders created by the context-manager classes are deleted when the block ends, even if an exception occurs. TemporaryFilemay have no name at all on Unix (it is unlinked right away), sof.nameis not a usable path. UseNamedTemporaryFilewhen another program needs the path.- Windows and reopening. A
NamedTemporaryFilethat is still open generally cannot be opened a second time by name on Windows. Close it first withdelete=False(and delete it yourself), or usedelete_on_close=Falseon Python 3.12+. mkstemp()andmkdtemp()do not clean up. You own the result and must remove it.mkstempalso leaves you an open file descriptor to close, for instance viaos.fdopen.- Security. The created file has restrictive permissions (readable only by the current user), and the name is unpredictable. Do not use the deprecated
mktemp(), which only invents a name and invites race conditions. - Where it lives.
gettempdir()looks at theTMPDIR,TEMPandTMPenvironment variables first, then system defaults. Large temporary files can fill a small/tmp; passdir=to choose a roomy disk. SpooledTemporaryFilekeeps data in memory until it exceedsmax_size, then moves it to disk; handy for uploads of unknown size.- Version notes.
NamedTemporaryFile(delete_on_close=...)andTemporaryDirectory(delete=False)were added in Python 3.12; check your version before relying on them.