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

Python basic tutorial

Python flow control

Funções no Python

Tipos de Dados do 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-of-file (EOF) character) and return a list, which can be processed by Python's for... in ... structure.

If it encounters the end-of-file (EOF) character, 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:pt.oldtoolbag.com
2:pt.oldtoolbag.com
3:pt.oldtoolbag.com
4:pt.oldtoolbag.com
5:pt.oldtoolbag.com

Loop to read the content of the file:

Online example

# Open file
fo = open("w3codebox.txt, "r")
print("The file name is: ", fo.name)
 
for line in fo.readlines():                         # Read each line sequentially  
    line = line.strip()                             # Remove leading and trailing whitespaces  
    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:pt.oldtoolbag.com
The data read is: 2:pt.oldtoolbag.com
The data read is: 3:pt.oldtoolbag.com
The data read is: 4:pt.oldtoolbag.com
The data read is: 5:pt.oldtoolbag.com

Python File (File) Method