方法簽名
file.next() -> str # Python 2
# Python 3: 使用 next(file) 內建函式,或 for line in file:
行為
- 檔案物件本身即為迭代器,實作
__iter__ 回傳 self、__next__ 回傳下一行。
- 每次呼叫回傳下一行(含尾端
\n),到達 EOF 拋出 StopIteration。
- 不可與
readline() 混用:內部預讀緩衝會導致資料遺漏或重複。
seek() 會清空預讀緩衝,安全重置位置。
範例:手動迭代前 5 行
with open("foo.txt", "r") as f:
for i in range(5):
try:
line = next(f)
print(f"Line {i}: {line.rstrip()}")
except StopIteration:
print("檔案少於 5 行")
break
輸出
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
Python 2 vs 3 差異
| Python 2 | Python 3 |
| 方法名 | f.next() | f.__next__() / next(f) |
| 迭代協定 | __iter__, next() | __iter__, __next__() |
| 通用寫法 | for line in f: (兩版皆適用) |
最佳實踐
- 優先使用
for line in f:,簡潔且自動處理 StopIteration。
- 需手動控制迭代時,用
next(f) (Py3) 配合 try/except StopIteration。
- 若中途
seek(),後續 next() 正常運作(緩衝已重置)。
- 二進制模式下
next(f) 回傳 bytes,文字模式回傳 str。
自訂迭代器模式
class LineNumberer:
def __init__(self, fileobj):
self.file = fileobj
self.lineno = 0
def __iter__(self):
return self
def __next__(self):
line = next(self.file)
self.lineno += 1
return f"{self.lineno:4}: {line}"
with open("foo.txt") as f:
for numbered in LineNumberer(f):
print(numbered, end="")