In today’s article, we will learn about the next method in python. Before entering the article, we must first know what the pythonnext method is and the next() method. What is it used for, where can it be used in python programming, and what role can it play. We can learn about these things in today’s article.
Overview
The next() method is used when the file uses an iterator. In a loop, the next() method will be called in each loop. The method returns the next line of the file. If the end (EOF) is reached, StopIteration is triggered.
Syntax
next() The method syntax is as follows:
fileObject.next();
Return value
#Returns the next line of the file.
Example
The following example demonstrates the use of the next() method:
The content of the file runoob.txt is as follows:
这是第一行 这是第二行 这是第三行 这是第四行 这是第五行
Loop to read the contents of the file:
# !/usr/bin/python # -*- coding: UTF-8 -*- # 打开文件 fo = open("runoob.txt", "rw+") print "文件名为: ", fo.name for index in range(5): line = fo.next() print "第 %d 行 - %s" % (index, line) # 关闭文件 fo.close()
The output result of the above example is:
文件名为: runoob.txt 第 0 行 - 这是第一行 第 1 行 - 这是第二行 第 2 行 - 这是第三行 第 3 行 - 这是第四行 第 4 行 - 这是第五行
In this article, we understand what the next() method is. If you don’t understand, in fact You can try it yourself. After all, hands-on practice is the best way to verify what you have learned. Finally, I hope this article can bring some help to you who are learning python.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
The above is the detailed content of What is the use of python next() method? Example analysis python next() method definition and function. For more information, please follow other related articles on the PHP Chinese website!