next() 方法(Python 2 為 file.next(),Python 3 為 file.__next__() 或內建 next(file))用於在檔案物件作為迭代器時,取得下一行。配合 for 迴圈或手動呼叫實現逐行讀取,遇 EOF 拋出 StopIteration 異常。
# Python 2
line = fileObject.next()
# Python 3
line = next(fileObject)
# 或
line = fileObject.__next__()
StopIteration。
with open('foo.txt', 'w') as f:
for i in range(1, 6):
f.write(f'Line {i}\n')
with open('foo.txt', 'r') as f:
for i in range(5):
line = next(f)
print(f"Line No {i} - {line.rstrip()}")
# 輸出:
# Line No 0 - Line 1
# Line No 1 - Line 2
# Line No 2 - Line 3
# Line No 3 - Line 4
# Line No 4 - Line 5
for line in f: 內部自動呼叫 iter(f) 取得迭代器(檔案物件本身),再重複呼叫 next() 直到捕獲 StopIteration。兩者等價,for 更簡潔安全。
try/except StopIteration 處理檔案結束邏輯。
def parse_records(filepath):
with open(filepath) as f:
while True:
try:
header = next(f).strip()
except StopIteration:
break
if not header.startswith('RECORD:'):
continue
record_id = header.split(':')[1]
data_lines = []
for _ in range(3): # 每筆記錄固定 3 行資料
try:
data_lines.append(next(f).rstrip())
except StopIteration:
data_lines.append('') # 不足補空
yield record_id, data_lines
for rid, data in parse_records('records.txt'):
print(f"ID: {rid}, Data: {data}")
next() 與 readline() 混用會導致預讀緩衝區不一致(資料丟失或重複)。選擇其一風格。seek() 重新定位指標會清除預讀緩衝區,後續 next() 從新位置讀取。rb) 下 next() 回傳 bytes,按 \n 分割。| 特性 | Python 2 | Python 3 |
|---|---|---|
| 方法名 | f.next() | f.__next__() / next(f) |
| 回傳型別 | str (bytes) | str (text) / bytes (binary) |
| 通用寫法 | next(f) (Py2.6+ 支援內建 next) | |
next() 是檔案迭代器的核心方法。日常開發優先使用 for line in f:;僅在需要精細控制讀取流程(預讀、條件跳過、多行解析)時手動呼叫 next()。注意與 readline() 不可混用,並在 Python 2/3 間統一使用內建 next() 函式。