English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python file readlines() usage and example

Python File (File) Method

Overview

readlines() The method is used to read all lines (until the end symbol EOF) and return a list, which can be processed by Python's for... in ... structure.

If it encounters the end symbol EOF, it returns an empty string.

Syntax

readlines() method syntax is as follows:

fileObject.readlines( );

Parameter

  • None.

Return value

Returns a list containing all lines.

Example

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

File w3The content of codebox.txt is as follows:

1:fr.oldtoolbag.com
2:fr.oldtoolbag.com
3:fr.oldtoolbag.com
4:fr.oldtoolbag.com
5:fr.oldtoolbag.com

Loop to read the content of the file:

Online Example

# Open the file
fo = open("w3codebox.txt, \
print("The file name is: ", fo.name)
 
for line in fo.readlines():                         # Read each line sequentially  
    line = line.strip()                             # Remove the blank spaces 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:
The file name is:  w3codebox.txt
The data read is: 1:fr.oldtoolbag.com
The data read is: 2:fr.oldtoolbag.com
The data read is: 3:fr.oldtoolbag.com
The data read is: 4:fr.oldtoolbag.com
The data read is: 5:fr.oldtoolbag.com

Python File (File) Method