首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python 文件写入优化

Python 文件写入优化

作者头像
小田测测看
发布2026-06-17 17:24:13
发布2026-06-17 17:24:13
1070
举报

在编写测试case中,可能存在大量写入文件的需求,以下是比较常见的写法

代码语言:javascript
复制
with open('output.txt', 'w') as f:
    f.write("Line 1\n")
    f.write("Line 2\n")
    f.write("Line 3\n")

这种写法存在三个主要问题:

  1. 1. 多次系统调用:每次 write() 都会触发系统级 I/O 操作
  2. 2. 小量写入:频繁写入小块数据效率低下
  3. 3. 缓冲区浪费:未充分利用 Python 的文件缓冲机制

优化方案

方案1:字符串拼接

代码语言:javascript
复制
# 一次性构建内容再写入
withopen('output.txt', 'w') as f:
    content = "\n".join([
        "Line 1",
        "Line 2",
        "Line 3"
    ])
    f.write(content + "\n")  # 添加结尾换行符
    
# 或使用 += 操作符(增量构建)
withopen('output.txt', 'w') as f:
    content = ""
    content += "Line 1\n"
    content += "Line 2\n"
    content += "Line 3\n"
    f.write(content)

方案2:writelines 方法

代码语言:javascript
复制
# 直接写入可迭代对象
lines = [
    "Line 1\n",
    "Line 2\n",
    "Line 3\n"
]

withopen('output.txt', 'w') as f:
    f.writelines(lines)
    
# 动态生成内容
withopen('output.txt', 'w') as f:
    f.writelines(
        f"Line {i}\n"for i inrange(1, 1001)
    )

方案3:缓冲写入

代码语言:javascript
复制
BUFFER_SIZE = 8192  # 8KB缓冲区

withopen('large_file.txt', 'w') as f:
    buffer = []
    current_size = 0
    
    for i inrange(1, 100000):
        line = f"Data line {i}\n"
        line_size = len(line.encode('utf-8'))
        
        if current_size + line_size > BUFFER_SIZE:
            # 缓冲区满时写入
            f.write(''.join(buffer))
            buffer = []
            current_size = 0
            
        buffer.append(line)
        current_size += line_size
    
    # 写入剩余内容
    if buffer:
        f.write(''.join(buffer))

方案4:使用 StringIO

代码语言:javascript
复制
from io import StringIO

# 在内存中构建内容
buffer = StringIO()
buffer.write("Line 1\n")
buffer.write("Line 2\n")
buffer.write("Line 3\n")

# 一次性写入磁盘
with open('output.txt', 'w') as f:
    f.write(buffer.getvalue())

# 清空缓冲区重用
buffer.seek(0)
buffer.truncate(0)

方案5:高级缓冲控制

代码语言:javascript
复制
# 设置自定义缓冲区大小
with open('output.txt', 'w', buffering=65536) as f:  # 64KB缓冲区
    for i in range(1, 1001):
        f.write(f"Line {i}\n")
        
# 手动刷新控制
with open('output.txt', 'w') as f:
    for i in range(1, 1001):
        f.write(f"Line {i}\n")
        if i % 100 == 0:  # 每100行刷新一次
            f.flush()

#Python

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-07-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程拾光 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 优化方案
    • 方案1:字符串拼接
    • 方案2:writelines 方法
    • 方案3:缓冲写入
    • 方案4:使用 StringIO
    • 方案5:高级缓冲控制
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档