Python 檔案 next() 方法



Python 檔案的 next() 方法返回檔案指標當前位置之後的下一行輸入。此方法在 Python 中用於迭代器,通常在迴圈中重複呼叫,直到到達檔案末尾返回所有檔案行。當指標到達 EOF(或檔案末尾)時,該方法會引發 StopIteration 異常。

將 next() 方法與其他檔案方法(如 readline())結合使用無法正常工作。但是,使用 seek() 將檔案位置重新定位到絕對位置將重新整理預讀緩衝區。

注意:此方法僅在 Python 2.x 中有效,在 Python 3.x 中無效。在 Python 3.x 中使用的替代方法是 readline() 方法。

語法

以下是 Python 檔案 next() 方法的語法:

fileObject.next(); 

引數

此方法不接受任何引數。

返回值

此方法返回下一行輸入。

示例

假設這是一個示例檔案,其行將由 Python 檔案 next() 方法使用迭代器返回。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例演示了 next() 方法的使用。藉助 for 迴圈,我們使用 next() 方法訪問檔案的所有行。列印檔案中的所有內容,直到該方法引發 StopIteration 異常。此示例僅在 Python 2.x 中有效。

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name 

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

for index in range(5):
   line = fo.next()
   print "Line No %d - %s" % (index, line)

# Close opened file
fo.close()

當我們執行上述程式時,它會產生以下結果:

Name of the file:  foo.txt
Line No 0 - This is 1st line

Line No 1 - This is 2nd line

Line No 2 - This is 3rd line

Line No 3 - This is 4th line

Line No 4 - This is 5th line

示例

現在讓我們嘗試使用此方法的替代方法 readline() 方法,用於 Python 3.x。

我們使用包含相同內容的相同檔案,但使用 readline() 方法代替。獲得的輸出將與 next() 方法相同。

# Open a file
fo = open("foo.txt", "r")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

for index in range(5):
   line = fo.readline()
   print("Line No %d - %s" % (index, line))

# Close opened file
fo.close()

如果我們編譯並執行上面的程式,則會產生如下結果:

Name of the file:  foo.txt
Line No 0 - This is 1st line

Line No 1 - This is 2nd line

Line No 2 - This is 3rd line

Line No 3 - This is 4th line

Line No 4 - This is 5th line
python_file_methods.htm
廣告