当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python File next()用法及代码示例



描述

Python文件方法next()当文件用作迭代器时使用,通常在循环中,重复调用 next() 方法。此方法返回下一个输入行,或在命中 EOF 时引发 StopIteration。

将 next() 方法与其他文件方法(如 readline())结合使用是行不通的。但是,将文件重新定位到绝对位置的 usingseek() 将刷新 read-ahead 缓冲区。

用法

以下是语法next()方法≫

fileObject.next(); 

参数

  • NA

返回值

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

示例

下面的例子展示了 next() 方法的用法。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python

# 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 opend 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 next() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。