Python File ReadLines () How to use

Source: Internet
Author: User
The ReadLines () method is used to read all rows (until the Terminator is EOF) and return the list, which can be made by Python for ... in ... The structure is processed and if the Terminator is encountered, an empty string is returned, and the desired friend can refer to the following

Overview

readlines() method is used to read all rows (until the end of EOF) and to return the list, which can be made by Python for ... in ... Structure for processing.

Returns an empty string if the Terminator EOF is encountered.

Grammar

readlines() The method syntax is as follows:

Fileobject.readlines ();

Parameters
No.

return value
Returns a list that contains all the rows.

Instance
The following example demonstrates the use of the ReadLine () method:

The contents of the file Jb51.txt are as follows:

1:www.jb51.net
2:www.jb51.net
3:www.jb51.net
4:www.jb51.net
5:www.jb51.net

To iterate through the contents of a file:

The writing of Python2

#!/usr/bin/python#-*-coding:utf-8-*-# Open File fo = open ("Jb51.txt", "R") print "file name:", Fo.name for line in Fo.readlines ( ):             #依次读取每行 Line   = Line.strip ()               #去掉每行头尾空白   print "read data:%s"% (line) # Close file Fo.close ()

The writing of Python3

#-*-coding:utf-8-*-# Open File fo = open ("Jb51.txt", "R") print ("File name:", Fo.name) for line in Fo.readlines ():             #依次读取每行 
  
   line = Line.strip ()               #去掉每行头尾空白   print ("Read data:%s"% (line)) # Close file Fo.close ()
  

The effect is as shown



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.