Python3 File readlines() Method

Python3 File(文件) 方法Python3 File Methods


Overview

readlines()The method is used to read all lines (until the end-of-file marker EOF) and return a list, which can be processed by Python's for... in ... structure. If the EOF marker is encountered, an empty string is returned.

If the EOF marker is encountered, an empty string is returned.

Syntax

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

fileObject.readlines( );

Parameters

  • None.

Return Value

Returns a list containing all the lines.

Example

The following example demonstrates the use of the readline() method:

The content of the file example.txt is as follows:

1:www.example.com
2:www.example.com
3:www.example.com
4:www.example.com
5:www.example.com

Read the content of the file in a loop:

Example (Python 3.0+)

#!/usr/bin/python3 # Open the file fo = open("example.txt", "r") print ("The file name is:", fo.name) for line in fo.readlines(): # Read each line in sequence line = line.strip() # Remove whitespace at the beginning and end of each line print ("The data read is: %s" % (line)) # Close the file fo.close()

The output result of the above example is:

文件名为:  example.txt
读取的数据为: 1:www.example.com
读取的数据为: 2:www.example.com
读取的数据为: 3:www.example.com
读取的数据为: 4:www.example.com
读取的数据为: 5:www.example.com

Python3 File(文件) 方法Python3 File Methods

Other Extensions