Python檔next()方法

Python 3中的File對象不支持next()方法。 Python 3有一個內置函數next(),它通過調用其next ()方法從迭代器中檢索下一個專案。 如果給定了默認值,則在迭代器耗盡返回此默認值,否則會引發StopIteration。 該方法可用於從檔對象讀取下一個輸入行。

語法

以下是next()方法的語法 -

next(iterator[,default])

參數

  • iterator − 要讀取行的檔對象
  • default − 如果迭代器耗盡則返回此默認值。 如果沒有給出此默認值,則拋出 StopIteration 異常

返回值

  • 此方法返回下一個輸入行

示例

假設’foo.txt’檔中包含以下行 -

C++
Java
Python
Perl
PHP

以下示例顯示了next()方法的用法。

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

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

# Close opened file
fo.close()

執行上面代碼後,將得到以下結果 -

Name of the file:  foo.txt
Line No 0 - C++

Line No 1 - Java

Line No 2 - Python

Line No 3 - Perl

Line No 4 - PHP

上一篇: Python檔對象方法 下一篇: Python os模組方法