Latest web development tutorials

Python File next () method

Python File (File) method Python File (File) method


Outline

next () method when the file using an iterator will be used to, in a loop, next () method will be called in each cycle, the method returns the next line of the file, if you reach the end (EOF), the trigger StopIteration

grammar

next () method has the following syntax:

fileObject.next(); 

parameter

  • no

return value

Returns the file the next line.

Examples

The following example demonstrates the next () method of use:

W3big.txt content file as follows:

这是第一行
这是第二行
这是第三行
这是第四行
这是第五行

Loop reads the contents of the file:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("w3big.txt", "rw+")
print "文件名为: ", fo.name

for index in range(5):
    line = fo.next()
    print "第 %d 行 - %s" % (index, line)

# 关闭文件
fo.close()

The above example output is:

文件名为:  w3big.txt
第 0 行 - 这是第一行

第 1 行 - 这是第二行

第 2 行 - 这是第三行

第 3 行 - 这是第四行

第 4 行 - 这是第五行

Python File (File) method Python File (File) method