Python tempfile.TemporaryFile
Write to a temporary text file and close it automatically when the work finishes.
A simple example
tempfile.TemporaryFile
- Start with An empty temporary file
- Do this Write A, rewind, then read
- Result A
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.pyStage 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 tempfile import TemporaryFile
with TemporaryFile(mode="w+", encoding="utf-8") as receipt:
receipt.write("paid")
receipt.seek(0)
print(receipt.read())
paid
Writing moves the file position forward. Seeking to the beginning makes the stored receipt readable.
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?
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?
What to watch for
The file is temporary. Copy data to the intended destination before the context closes.