← 中文资源

简体中文版本

tempfile 管理一次性工作文件

用 TemporaryDirectory 自动清理目录树、NamedTemporaryFile 预留唯一文件名、mkstemp 交出完全控制权。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

tempfile 管理一次性工作文件以函数 main为骨架。

使用要点

  • 直接运行文件,输出会带上标签,比如 staged exists:、export suffix:、spare log is temp:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「tempfile 管理一次性工作文件」会打印什么?

运行文件本身,staged exists:、export suffix:、spare log is temp: 这些前缀各对应一段演示逻辑。

核心语句

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')

代码示例

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()