Python File next() 方法



Python File next() 方法返回关于文件中文件指针当前位置的下一个输入行。Python 中的此方法用于迭代器中,通常在循环中,在迭代器中,它会被重复调用并返回文件的所有行,直到它到达文件末尾。当指针命中 EOF(或文件末尾)时,该方法将引发 StopIteration。

next() 方法与其他文件方法(如 readline() )组合在一起无法正常工作。但是,使用 seek() 将文件位置重新定位到绝对位置将刷新预读缓冲区。

注意:此方法仅适用于 Python 2.x,不适用于 Python 3.x。在 Python 3.x 中使用此方法的另一种方法是 readline() 方法。

语法

以下是 Python File next() 方法的语法 -


 fileObject.next();

参数

该方法不接受任何参数。

返回值

此方法返回下一个输入行。

假设这是一个示例文件,其行将由 Python File 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

现在让我们尝试使用此方法的替代方案,即 Python 3.x 的 readline() 方法。

我们使用的是包含相同内容的相同文件,但使用的是 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