Python3 file.next()方法

在 Python3 中文件对象不支持 next()方法。Python3 的内置函数 next() ,它通过调用 __next__() 方法从迭代器读取下一个项目。如果 default 给定,如果迭代器用尽它被返回,否则引发 StopIteration 异常。 这种方法可用于读取来自文件对象下一个输入行。

语法

以下是 next()方法的语法 -
next(iterator[,default])

参数

  • iterator : 从中要读取行的文件对象

  • default : 如果迭代耗尽则返回。如果没有给出则将引发StopIteration异常

返回值

此方法返回下一输入行。

示例

下面的示例演示 next()方法的使用。
Assuming that 'foo.txt' contains following lines
C++
Java
Python
Perl
PHP
#!/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

上一篇: Python3模块 下一篇: Python3文件方法