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
广告