Python3 File readlines() Method
Overview
readlines() The method reads all lines (up to the EOF terminator) and returns a list, which can be processed by Python's for... in ... structure. If EOF is encountered, an empty string is returned.
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 shows how to use the readline() 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 (Python 3.0+)
#!/usr/bin/python3
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
Python3 File methods