Tutorial on manipulating files in Python using the next () method

Source: Internet
Author: User
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 row, or the stopiteration exception is thrown when EOF is hit.

The method with other files, such as ReadLine (), is not working properly with the next () method. However, Usingseek () repositions the file to an absolute location refreshes the read-ahead buffer.
Grammar

The following is the syntax for the next () method:

Parameters

    • NA

return value

This method returns the next input row.
Example

The following example shows the use of the next () method.

#!/usr/bin/python# Open a filefo = open ("Foo.txt", "rw+") print "Name of the file:", fo.name# assuming file has following 5 lines# This was 1st line# this is 2nd line# This is 3rd line# This is 4th line# this is 5th linefor index in range (5): 
  line = Fo.next ()  print "line No%d-%s"% (index, line) # Close opend filefo.close ()

When we run the above program, it produces the following results:

Name of the File:foo.txtLine no 0-this is 1st Lineline no 1-this are 2nd lineline no 2-this is 3rd lineline no 3-t He is 4th Lineline No 4-this are 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.