Use the next () method to operate files in Python

Source: Internet
Author: User

Use the next () method to operate files in Python

This article describes how to use the next () method to operate files in Python. It is a basic knowledge in Python. For more information, see

Next () method when a file is used as an iterator, a typical example is used in a loop, and the next () method is called repeatedly. This method returns the next input line, or is hit when the StopIteration exception EOF is thrown.

The next () method is not working properly with other file methods, such as ReadLine. However, usingseek () refresh the pre-read buffer by redirecting the file to an absolute position.

Syntax

The syntax of the next () method is as follows:

?

1

FileObject. next ();

Parameters

NA

Return Value

This method returns the next input line.

Example

The following example shows how to use the next () method.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#! /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 ()

When we run the above program, it will produce the following results:

?

1

2

3

4

5

6

7

8

9

10

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.