Python File readlines() Method
Overview
readlines()The method is used to read all lines (until the end-of-file EOF) and return a list, which can be processed by Python's for... in ... structure.
If the end-of-file EOF 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 readlines() 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
Loop through the contents of the file:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Open file
fo = open("example.txt", "r")
print "File name:", fo.name
for line in fo.readlines(): # Read each line in sequence
line = line.strip() # Strip leading and trailing whitespace from 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.comOther Extensions
Python File Methods