萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 檔案操作 writelines() 方法詳解:批量寫入序列、無自動換行

方法簽名

file.writelines(sequence_of_strings) -> None

關鍵特性

  • 接受任何可迭代物件(list、tuple、generator),元素必須為字串(文字模式)或位元組(二進制模式)。
  • 不自動加入分隔符或換行,需自行在元素中包含 \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

write() vs writelines() 效能比較

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()。
copyright © 萬盛學電腦網 all rights reserved