Python File readlines() method
Overview
readlines() This method reads all lines (until the end-of-file marker EOF) and returns a list, which can be processed by Python's for... in ... structure.
If EOF is encountered, an empty string is returned.
Syntax
The readlines() method syntax is as follows:
fileObject.readlines( );
Parameters
-
none.
Return Value
Returns a list containing all lines.
Example
The following example demonstrates the use of the readlines() method:
The contents of the runoob.txt file are as follows:
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
Read the file's contents in a loop:
Example
#!/usr/bin/python
-- coding: UTF-8 --
Opening a File
fo
=
open
(
"
runoob.txt
"
,
"
r
"
)
"
File name:
"
,
fo
.
name
for
line
in
fo
.
readlines
(
)
:
#Read each line in turn
line
=
line
.
strip
(
)
#Strip leading and trailing whitespace from each line
"
The data read is: %s
"
%
(
line
)
Closing a File
fo
.
close
(
)
The output of the above example is:
文件名为: runoob.txt
读取的数据为: 1:www.runoob.com
读取的数据为: 2:www.runoob.com
读取的数据为: 3:www.runoob.com
读取的数据为: 4:www.runoob.com
读取的数据为: 5:www.runoob.com
Python File methods