Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python file readlines() method is used to read lines until the end of file object and return list containing the lines thus read. The method has an optional parameter which is used to specify number of bytes to read and if the total number of bytes returned exceeds the specified number, no more lines are returned.

Syntax

file.readlines(sizehint)

Parameters

sizehint Optional. Specify number of bytes. If the total number of bytes returned exceeds the specified number, no more lines are returned. Default is -1 which means the whole file.

Return Value

Returns the list containing the lines.

Example: Read whole file

In the below example, the readlines() method is used to read the whole content of the file called MyFile.

MyFile = open("python_test.txt", "r")

#Assuming the file contains
#This is line 1 content.
#This is line 2 content.
#This is line 3 content.

#read whole content of the file
print(MyFile.readlines())

The output of the above code will be:

['This is line 1 content.\n', 'This is line 2 content.\n', 'This is line 3 content.']

Example: Use sizehint of readlines()

In the below example, sizehint parameter is used to specify the number of byte. After returning first line of MyFile, the total number of bytes returned exceeds the specified number 10, hence no more line is returned after that.

MyFile = open("python_test.txt", "r")

#Assuming the file contains
#This is line 1 content.
#This is line 2 content.
#This is line 3 content.

print(MyFile.readlines(10))

The output of the above code will be:

['This is line 1 content.\n']

❮ Python File Handling Methods