Python - File readlines() Method


Advertisements

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.

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")
#read whole content of the file
print(MyFile.readlines())

Output

['Python is a programming language.\n', 'Learning Python is fun.']

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")

print(MyFile.readlines(10))

Output

['Python is a programming language.\n']

Python File Handling Methods
Advertisements