您现在的位置是:网站首页 > 博客日记 >

python临时文件和目录模块-tempfile

作者:YXN-python 阅读量:37 发布日期:2026-01-08

1. 创建临时文件

import tempfile

# 创建临时文件(自动删除)
with tempfile.TemporaryFile(mode='w+') as tmp:
    tmp.write('Hello, World!')
    tmp.seek(0)
    print(tmp.read())  # 输出: Hello, World!
# 文件在退出 with 块后自动删除

 

2. 创建带后缀/前缀的临时文件

import tempfile

# 创建带后缀的临时文件
with tempfile.NamedTemporaryFile(
    suffix='.txt',
    prefix='temp_',
    delete=False,  # 不自动删除,手动管理
    dir='D:/'  # 指定临时目录
) as tmp:
    print(f"临时文件路径: {tmp.name}")
    tmp.write(b"Temporary data")
    
# delete=False 时需要手动清理
import os
os.unlink(tmp.name)

 

3. 创建临时目录

import tempfile
import os

with tempfile.TemporaryDirectory() as tmpdir:
    print(f"临时目录: {tmpdir}")
    
    # 在临时目录中创建文件
    temp_file = os.path.join(tmpdir, 'test.txt')
    with open(temp_file, 'w') as f:
        f.write('Temporary content')
    
    # 使用文件...
    
# 目录及其内容自动删除

 

4. 获取临时目录路径

import tempfile

# 获取系统临时目录路径
temp_dir = tempfile.gettempdir()
print(f"系统临时目录: {temp_dir}")

# 获取用户级临时目录
temp_dir = tempfile.gettempdirb()  # bytes 版本

 

 

YXN-python

2026-01-08