Python: Roll a spooled temporary file over explicitly
tempfile.SpooledTemporaryFile() can keep a small binary buffer in memory and move it to an operating-system-backed temporary file. Call rollover() when a downstream consumer needs file-backed storage before the size threshold is reached.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as spool_rollover.py in an empty working directory:
import os
from tempfile import SpooledTemporaryFile
with SpooledTemporaryFile(max_size=1024, mode="w+b") as stream:
stream.write(b"report\n")
before = stream.tell()
stream.rollover()
print("Position preserved:", stream.tell() == before)
print("Disk file bytes:", os.fstat(stream.fileno()).st_size)
stream.seek(0)
print("Read back:", repr(stream.read()))
print("Closed:", stream.closed)Run it without -O so any assertions remain enabled:
python3 spool_rollover.pyCaptured output:
Position preserved: True
Disk file bytes: 7
Read back: b'report\n'
Closed: TrueThe seven-byte buffer is below max_size=1024, so the explicit call causes rollover. The cursor remains at the same position, and seeking back allows the original bytes to be read. Exiting the context closes the temporary file.
Limits and cleanup
Calling fileno() also causes rollover if it has not happened yet. The output’s disk-file label refers to the OS-backed file; a temporary directory may itself use memory-backed storage. The threshold is not a cap on total file size. Do not rely on private attributes to inspect the backing object.
After testing, remove the example script from its working directory:
rm -- spool_rollover.pyReference
Acknowledgements
This post was created with assistance from AI.