file.writelines(sequence_of_strings) -> None
\n。#!/usr/bin/env python3
with open("foo.txt", "r+") as f:
print(f"檔案: {f.name}")
f.seek(0, 2) # 移至末尾
lines = ["This is 6th line\n", "This is 7th line\n"]
f.writelines(lines)
f.seek(0)
for i, line in enumerate(f):
print(f"Line {i}: {line.rstrip()}")
檔案: foo.txt
Line 0: This is 1st line
Line 1: This is 2nd line
Line 2: This is 3rd line
Line 3: This is 4th line
Line 4: This is 5th line
Line 5: This is 6th line
Line 6: This is 7th line
import time, io
data = [f"line {i}\n" for i in range(100000)]
# 1. 迴圈 write
with io.StringIO() as f:
t0 = time.perf_counter()
for line in data: f.write(line)
print(f"loop write: {(time.perf_counter()-t0)*1000:.1f} ms")
# 2. writelines
with io.StringIO() as f:
t0 = time.perf_counter()
f.writelines(data)
print(f"writelines: {(time.perf_counter()-t0)*1000:.1f} ms")
# 3. join + write
with io.StringIO() as f:
t0 = time.perf_counter()
f.write("".join(data))
print(f"join+write: {(time.perf_counter()-t0)*1000:.1f} ms")
典型結果:join+write ≈ writelines > loop write(約 2-3 倍差距)。
def generate_lines(n):
for i in range(n):
yield f"{i}\n"
with open("huge.txt", "w") as f:
f.writelines(generate_lines(10_000_000)) # 不會一次載入 1000 萬字串到記憶體
int 列表) → TypeError。\n 導致內容連在一起。str → TypeError: a bytes-like object is required,需 s.encode()。