Python Create Temp File with NamedTemporaryFile
Create a UTF-8 temporary file, read it from the correct cursor position, and clean it up automatically.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Python Create Temp File with NamedTemporaryFile
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
To create a temporary file in Python, use tempfile.NamedTemporaryFile when you need both a file object and a filesystem name. Use a context manager so the file closes and is removed at the end of the block. The default mode is binary; choose mode='w+' and encoding='utf-8' for a text round trip. Unlike a hard-coded path such as temp.txt, this creates a unique name in the system's temporary location. NamedTemporaryFile chooses a unique path and gives you an open file handle. Its default binary mode does not suit ordinary text; set mode='w+' and encoding='utf-8'.
- 00:43
The plus sign permits reading as well as writing. The with statement owns cleanup, so the example returns the needed content while the file still exists. Notice that the system chooses the actual temporary directory and a collision- resistant filename. We do not have to guess whether another run already created temp.txt. The temporary file is meant to be short lived, so returning its name after the with block would give the caller a path to something that no longer exists. Return the processed content or write a separate final output instead. A file has a cursor. Immediately after write(), the cursor is at the end, so read() returns an empty
- 01:23
string. Call seek(0) before reading. This is the deliberately broken case in the video and the practical exercise. The returned name is useful for diagnostics, but a temporary name is not a permanent storage location. Write Café and seek to position zero before reading. The output makes the round trip observable without relying on a fixed filename. In a long-running program, avoid storing temp.name as if it were a durable path. A different process that must reopen the file needs a carefully designed lifecycle, especially on Windows. The first read happens with the cursor at the end of the file and returns an empty
- 02:05
string. That is not evidence that write failed. seek(0) resets the position, and the second read returns the text. When a file is used for both reading and writing, cursor position is part of the program state. Inside the with block you can inspect file.name and read from the same open handle. After leaving the block the file should be closed and deleted. On Windows, reopening a NamedTemporaryFile by name while it is still open has additional sharing rules. The lesson avoids that portability trap by reading from the handle it already owns. If a second program must open a path, a TemporaryDirectory and a normal file
- 02:47
inside it is often easier to coordinate. Run the same experiment with an empty string: the read is empty both before and after seek, so include a nonempty fixture when diagnosing the cursor bug. For binary data use a binary mode and bytes instead; this lesson focuses on a text file with a known encoding. This page answers the temporary-file creation and lifecycle question. The related atomic-write lesson solves a different problem: replacing an existing destination without exposing a partial write. A temporary file alone does not make a write atomic.
- 03:27
Keep temporary work and final output separate, and test empty text as well as Unicode before using this pattern in a larger file workflow. The file exists inside its with block. After the handle closes, the default NamedTemporaryFile behavior removes it. The example checks existence on both sides of the block to make cleanup visible. This is suitable for scratch data that no caller needs after the function returns. The related tempfile atomic-write lesson creates a temporary sibling to replace a final file. That is a separate guarantee. If your program needs a second application to open a file by path while you still
- 04:09
hold it, consider TemporaryDirectory with a normal file and explicit coordination instead of assuming every platform permits another open on a NamedTemporaryFile. Repair round_trip_note(text) so it writes text to a named temporary file, seeks to the beginning, reads the same text, and lets the context manager clean up. The prepared run must print 'Café note'. Do not use a fixed filename or delete=False. There is a useful distinction between this pattern and using a temporary directory. NamedTemporaryFile gives you an already open handle. TemporaryDirectory gives you a folder where you can create and reopen several
- 04:49
ordinary files. Choose based on whether another tool needs a pathname or whether your own Python code can use the handle directly. On Windows, the latter choice avoids a common sharing surprise. At PythonLessonLab, work through the matching lesson and run the checked task. Explain the output before changing the code, then make one small change and rerun the boundary case. The result matters more than memorizing a function name: you should know what it accepts, what it returns, and which failure it prevents.
Understand the concept
To create a temporary file in Python, use tempfile.NamedTemporaryFile when you need both a file object and a filesystem name. Use a context manager so the file closes and is removed at the end of the block. The default mode is binary; choose mode='w+' and encoding='utf-8' for a text round trip. Unlike a hard-coded path such as temp.txt, this creates a unique name in the system's temporary location.
A file has a cursor. Immediately after write(), the cursor is at the end, so read() returns an empty string. Call seek(0) before reading. This is the deliberately broken case in the video and the practical exercise. The returned name is useful for diagnostics, but a temporary name is not a permanent storage location.
Inside the with block you can inspect file.name and read from the same open handle. After leaving the block the file should be closed and deleted. On Windows, reopening a NamedTemporaryFile by name while it is still open has additional sharing rules. The lesson avoids that portability trap by reading from the handle it already owns. If a second program must open a path, a TemporaryDirectory and a normal file inside it is often easier to coordinate.
This page answers the temporary-file creation and lifecycle question. The related atomic-write lesson solves a different problem: replacing an existing destination without exposing a partial write. A temporary file alone does not make a write atomic. Keep temporary work and final output separate, and test empty text as well as Unicode before using this pattern in a larger file workflow.
- NamedTemporaryFile creates a unique named file
- Text mode needs an encoding
- seek(0) resets the cursor before reading
- The context manager closes and removes the temporary file
See it step by step
Read the code, predict the output, then compare it with the result.
01. Create and read a named temporary file
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w+', encoding='utf-8') as temp:
temp.write('Café')
temp.seek(0)
print(temp.read())CaféText mode and an explicit encoding make the round trip clear.
02. Observe the cursor bug
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w+', encoding='utf-8') as temp:
temp.write('note')
print(repr(temp.read()))
temp.seek(0)
print(repr(temp.read()))''
'note'The second read starts at the beginning.
03. Confirm automatic cleanup
from pathlib import Path
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w+', encoding='utf-8') as temp:
name = temp.name
print(Path(name).exists())
print(Path(name).exists())True
FalseThe temporary file exists inside the block and is removed when it closes.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Create a UTF-8 temporary text file
NamedTemporaryFile chooses a unique path and gives you an open file handle. Its default binary mode does not suit ordinary text; set mode='w+' and encoding='utf-8'. The plus sign permits reading as well as writing. The with statement owns cleanup, so the example returns the needed content while the file still exists.
Write Café and seek to position zero before reading. The output makes the round trip observable without relying on a fixed filename. In a long-running program, avoid storing temp.name as if it were a durable path. A different process that must reopen the file needs a carefully designed lifecycle, especially on Windows.
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w+', encoding='utf-8') as temp:
temp.write('Café')
temp.seek(0)
print(temp.read())Café- Choose text mode and encoding.
- Write Unicode content.
- Seek to zero and read from the same handle.
Observe the file cursor before and after seek
The first read happens with the cursor at the end of the file and returns an empty string. That is not evidence that write failed. seek(0) resets the position, and the second read returns the text. When a file is used for both reading and writing, cursor position is part of the program state.
Run the same experiment with an empty string: the read is empty both before and after seek, so include a nonempty fixture when diagnosing the cursor bug. For binary data use a binary mode and bytes instead; this lesson focuses on a text file with a known encoding.
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w+', encoding='utf-8') as temp:
temp.write('note')
print(repr(temp.read()))
temp.seek(0)
print(repr(temp.read()))''
'note'- Predict the first read.
- Check the empty repr output.
- Reset the cursor and compare the second read.
Verify automatic deletion at context exit
The file exists inside its with block. After the handle closes, the default NamedTemporaryFile behavior removes it. The example checks existence on both sides of the block to make cleanup visible. This is suitable for scratch data that no caller needs after the function returns.
The related tempfile atomic-write lesson creates a temporary sibling to replace a final file. That is a separate guarantee. If your program needs a second application to open a file by path while you still hold it, consider TemporaryDirectory with a normal file and explicit coordination instead of assuming every platform permits another open on a NamedTemporaryFile.
from pathlib import Path
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w+', encoding='utf-8') as temp:
name = temp.name
print(Path(name).exists())
print(Path(name).exists())True
False- Record the generated name while open.
- Observe True inside the block.
- Observe False after close.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Keep the existing with block, add temp.seek(0) after temp.write(text), then call temp.read().
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Reading at end-of-file
temp.write(text)
return temp.read()temp.write(text)
temp.seek(0)
return temp.read()What happens: The result is an empty string.
Read from the beginning of the same open handle.
Treating a temporary name as permanent
return temp.namereturn temp.read()What happens: The caller receives a path that disappears after the context exits.
Return the data you need before closing, or use a documented persistent destination.