Library contents

Python tempfile.TemporaryFile

Write to a temporary text file and close it automatically when the work finishes.

A simple example

tempfile.TemporaryFile

  1. Start with An empty temporary file
  2. Do this Write A, rewind, then read
  3. Result A
Rewinding returns the read position to the beginning of the file.

Syntax

Python syntax
with TemporaryFile(mode="w+", encoding="utf-8") as receipt:
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Stage a receipt before exporting it

A receipt export needs intermediate storage before the final file is published. Create a temporary destination and release it when the export step finishes so another job can use its own workspace.

From the programwith TemporaryFile(mode="w+", encoding="utf-8") as receipt:
Resultpaid
lesson.py
from tempfile import TemporaryFile

with TemporaryFile(mode="w+", encoding="utf-8") as receipt:
    receipt.write("paid")
    receipt.seek(0)
    print(receipt.read())
Output
paid

Writing moves the file position forward. Seeking to the beginning makes the stored receipt readable.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?

GivenFile contents “clay”
Worked resultclay

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Save the note and read it back before the desk closes. Which characters are recovered?

GivenFile contents “ring bell”
Worked resultring bell

What to watch for

The file is temporary. Copy data to the intended destination before the context closes.

Documentation for tempfile.TemporaryFile