tempfile Stages Disposable Working Files

Stage disposable files with tempfile: TemporaryDirectory cleans whole trees, NamedTemporaryFile reserves a name, and mkstemp hands over full control.

PythonResilience

Code

pythonsnippet
30 lines
import tempfile
from pathlib import Path


def main() -> None:
    # TemporaryDirectory:退出 with 时整棵目录树自动删除
    with tempfile.TemporaryDirectory(prefix='stage-') as tmp:
        root = Path(tmp)
        staged = root / 'payload.bin'
        staged.write_bytes(b'round-trip payload')
        print('staged exists:', staged.exists(), '| bytes:', staged.stat().st_size)

        # NamedTemporaryFile:拿到唯一文件名,delete=False 保留到手动删除
        with tempfile.NamedTemporaryFile(prefix='export-', suffix='.json', delete=False) as handle:
            handle.write(b'{"ready": true}')
            name = handle.name
        print('export suffix:', Path(name).suffix, '| kept:', Path(name).exists())
        Path(name).unlink()

        # mkstemp:只要文件描述符 + 路径,由调用方全权管理
        fd, spare = tempfile.mkstemp(dir=tmp, suffix='.log')
        with open(fd, 'w', encoding='utf-8') as log:
            log.write('line one\n')
        print('spare log is temp:', Path(spare).name.startswith('tmp'), '| size:', Path(spare).stat().st_size)

    print('temp dir removed:', not Path(tmp).exists())


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

staged exists: True | bytes: 18
export suffix: .json | kept: True
spare log is temp: True | size: 8
temp dir removed: True

Inside the snippet

tempfile Stages Disposable Working Files is built around the function main.

Path are the only symbols borrowed from tempfile — the coupling is explicit and narrow.

What to watch for

  • Plan for an install step: tempfile is a real dependency, resolved by the package manager.

Putting it to use

Output lines are prefixed (staged exists:, export suffix:, spare log is temp:), making each step’s effect easy to spot.

Core lines

with tempfile.NamedTemporaryFile(prefix='export-', suffix='.json', delete=False) as handle:
    handle.write(b'{"ready": true}')
    name = handle.name
with open(fd, 'w', encoding='utf-8') as log:
    log.write('line one\n')

Interactive Tools for This Topic

FAQ

What does tempfile Stages Disposable Working Files print when run?
No setup needed: run the file and look for labeled lines like `staged exists:`, `export suffix:`, `spare log is temp:` in the output.