在编写测试case中,可能存在大量写入文件的需求,以下是比较常见的写法
with open('output.txt', 'w') as f:
f.write("Line 1\n")
f.write("Line 2\n")
f.write("Line 3\n")这种写法存在三个主要问题:
write() 都会触发系统级 I/O 操作# 一次性构建内容再写入
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)# 直接写入可迭代对象
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)
)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))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)# 设置自定义缓冲区大小
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