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模块方法