萬盛學電腦網

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

Python 檔案操作 readline() 方法:逐行讀取、保留換行符、size 限制長度

方法簽名

file.readline(size=-1) -> str/bytes

行為

  • 讀取一整行(含尾端 \n),除非檔案結尾無換行符。
  • size 指定最大位元組/字元數,若超過則在 size 處截斷(可能在行中間)。
  • EOF 立即回傳空字串 "" / b""。

範例

with open("foo.txt", "r") as f:
    line1 = f.readline()
    print(f"完整行: {repr(line1)}")  # 'This is 1st line\n'

    line2 = f.readline(5)
    print(f"前 5 字元: {repr(line2)}")  # 'This '

輸出

完整行: 'This is 1st line\n'
前 5 字元: 'This '

常見用法:逐行處理大檔案

with open("huge.log", encoding="utf-8") as f:
    while True:
        line = f.readline()
        if not line:
            break
        process(line.rstrip("\n"))

等價且更 Pythonic:

with open("huge.log", encoding="utf-8") as f:
    for line in f:
        process(line.rstrip("\n"))

readline() vs readlines() vs 迭代器

  • readline():單行、可控制最大長度、記憶體 O(1)。
  • readlines():一次全讀成列表、記憶體 O(N)、小檔隨機存取適合。
  • for line in f:語法糖,底層呼叫 readline(),記憶體 O(1)、最推薦。

size 參數實際用途

  • 防禦異常長行(如日誌竄改、壞掉的 CSV)導致記憶體暴增。
  • 解析固定寬度記錄格式(每筆 80 字元)。

二進制模式

with open("data.bin", "rb") as f:
    header = f.readline(4)  # 讀前 4 bytes
    assert header == b"MAGIC"
copyright © 萬盛學電腦網 all rights reserved