Accessing the elements of a file

Source: Internet
Author: User

If a file is named Nba.txt, the contents are as follows:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7F/77/wKiom1cfUfbBsUlKAAAlnrmz_hY842.png "title=" 1.png " alt= "Wkiom1cfufbbsulkaaalnrmz_hy842.png"/>

Under the Python 2.6

>>>file=open ("File path/nba.txt", "R") >>>for I in range (5): Name=file.next print (name)

The output results are as follows:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7F/74/wKioL1cfU2zwrPYqAAAc7c7ngnM122.png "title=" 1.png " alt= "Wkiol1cfu2zwrpyqaaac7c7ngnm122.png"/>

Under python 3.5 :

>>>file=open ("File path/nba.txt", "R") >>>name=file.readline () >>>print (name) LeBron James

Only the first line is displayed, even if you refresh print (name), it is LeBron James and not the second sentence.

>>>file=open ("File path/nba.txt", "R") >>>for I in range (6): Name=file.readline () print (name)

The output is:

LeBron James

Kobe Bryant

Allen Iverson

Steven Curry

Yao Ming

#这里有一个空行


If you use. Next () in 3.5, you cannot match the open function, and you will get an error: Attributeerror: ' _io. Textiowrapper ' object has no attribute ' next '

So it should be written in 3.5:

With open ("Path/nba.txt") as File:while true:name=next (file) print (name)

This is the output of the full text.

This article is from "Life is waiting for Gordo" blog, please make sure to keep this source http://chenx1242.blog.51cto.com/10430133/1768031

Accessing the elements of a file

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.