readline() 是 Python 文件物件專門用於「逐行讀取」的方法。它每次呼叫只回傳一行 (含結尾換行符),極適合處理大型文字文件、日誌分析、CSV 解析等逐行處理情境。本文詳細說明語法、參數、回傳值與豐富實戰範例。
file_object.readline(size=-1)
| 參數 | 說明 |
|---|---|
size (可選) | 最大讀取位元組數。若指定,可能回傳不完整行 (截斷於 size 限制)。預設 -1 讀取完整行。 |
\n (最後一行若無換行則不含)。'' (可作為迴圈終止條件)。str,二進位模式回傳 bytes。with open('access.log', 'r', encoding='utf-8') as f:
for line in f: # 文件物件本身可迭代,自動逐行
line = line.rstrip('\n') # 移除結尾換行符
if 'ERROR' in line:
print(f'錯誤行: {line}')
with open('data.txt', 'r') as f:
while True:
line = f.readline()
if not line: # EOF 回傳空字串
break
print(f'行號 {f.tell()}: {line}', end='')
with open('huge_line.txt', 'r') as f:
# 只讀取前 100 字元,避免單行過長佔滿記憶體
partial = f.readline(100)
print(f'前100字元: {partial}')
def process_large_file(filepath, chunk_lines=10000):
'''生成器:分批次產出行列表,適合批次寫入資料庫'''
batch = []
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
batch.append(line.rstrip('\n'))
if len(batch) >= chunk_lines:
yield batch
batch = []
if batch:
yield batch
# 使用範例
for batch in process_large_file('huge.csv'):
db.bulk_insert(batch)
print(f'已寫入 {len(batch)} 筆')
with open('data.csv', 'r') as f:
header = f.readline() # 讀取並捨棄第一行
print(f'欄位: {header.strip()}')
for line in f:
if line.startswith('#'): # 跳過註解行
continue
process_data(line)
with open('config.ini', 'r') as f:
for lineno, line in enumerate(f, 1):
line = line.strip()
if line and not line.startswith(';'):
print(f'{lineno:4d}: {line}')
| 方式 | 記憶體 | 速度 | 適用場景 |
|---|---|---|---|
for line in f | O(1) | 快 | 最通用、Pythonic、自動處理迭代器協定 |
f.readline() | O(1) | 快 | 需精確控制讀取邏輯 (如狀態機解析) |
f.readlines() | O(N) | 中 | 小文件需隨機存取行、或一次性載入列表 |
readline() 保留 \n,處理前記得 .rstrip('\n') 或 .strip()。'\n' (真值),EOF 回傳 '' (假值),if not line: 正確判斷 EOF。\r\n、\r 統一轉為 \n,跨平台無憂。for line in f: 簡潔迭代。readline()。readlines()。encoding='utf-8' 避免編碼問題。with 確保資源釋放。readline() 是 Python 文件處理的基石之一,掌握其行導向特性與生成器模式,能輕鬆應對 TB 級日誌分析、流式資料處理等高階場景。