首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 檔案操作:next() 方法逐行迭代讀取完整教學

     編輯:更多程式設計知識

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__()
  • 無參數。
  • 回傳下一行字串(含換行符)。
  • EOF 時拋出 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 迴圈

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 vs 3 差異

特性Python 2Python 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() 函式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved