How to Create a Temp File in Python Quickly and Safely
In Python, you can create a temporary file using the
tempfile module, specifically with tempfile.TemporaryFile() or tempfile.NamedTemporaryFile(). These functions create files that are automatically deleted when closed, useful for short-term storage.Syntax
The tempfile module provides functions to create temporary files. The main ones are:
tempfile.TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None): Creates a temporary file that is deleted as soon as it is closed.tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True): Creates a temporary file with a visible name in the file system, deleted by default on close.
Parameters like mode control how you read/write the file, and suffix, prefix, dir control the file name and location.
python
import tempfile # Create a temporary file temp = tempfile.TemporaryFile() # Write bytes to the file temp.write(b'Hello world!') # Move to the beginning to read temp.seek(0) # Read the content print(temp.read()) # Close the file (it will be deleted) temp.close()
Output
b'Hello world!'
Example
This example shows how to create a named temporary file, write text to it, read it back, and then close it so it is deleted automatically.
python
import tempfile with tempfile.NamedTemporaryFile(mode='w+', delete=True) as temp: temp.write('Temporary file content') temp.seek(0) content = temp.read() print('File content:', content) print('Temporary file name:', temp.name) # After the with block, the file is deleted automatically
Output
File content: Temporary file content
Temporary file name: /tmp/tmpabcdefg
Common Pitfalls
Common mistakes when using temporary files include:
- Not closing the file, which can leave temporary files lingering.
- Using
delete=Falseunintentionally, which keeps files after closing. - Trying to open the temporary file by name on some systems when
delete=Truebecause the file may be deleted immediately.
Always use with blocks to ensure files are closed and deleted properly.
python
import tempfile # Wrong: Not closing the file temp = tempfile.NamedTemporaryFile() temp.write(b'Hello') # File might not be deleted until program ends # Right: Using with block with tempfile.NamedTemporaryFile() as temp: temp.write(b'Hello') temp.seek(0) print(temp.read()) # File deleted here
Output
b'Hello'
Quick Reference
| Function | Description | Deletes File Automatically? |
|---|---|---|
| TemporaryFile() | Creates a temp file without a visible name | Yes, on close |
| NamedTemporaryFile() | Creates a temp file with a visible name | Yes, by default on close |
| mkstemp() | Creates a temp file and returns low-level file descriptor and name | No, you must delete manually |
| mkdtemp() | Creates a temp directory | No, you must delete manually |
Key Takeaways
Use the tempfile module to create temporary files safely in Python.
Prefer using with blocks to ensure temporary files are closed and deleted automatically.
TemporaryFile() creates unnamed temp files; NamedTemporaryFile() creates named temp files.
Be careful with the delete parameter to avoid leaving temp files on disk.
Temporary files are useful for short-term data storage during program execution.