Python Tutorial Python Advanced Python References Python Libraries

Python - File readlines() Method



The Python 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

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

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

#read the file
MyFile = open("test.txt", "r")
#read whole content of the file
print(MyFile.readlines())
MyFile.close()

The output of the above code will be:

['This is a test file.\n', 'It contains dummy content.']

Example: Use sizehint of readlines()

The readlines() method can also be used to read the partial content of the file. This can be achieved by specifying the number of bytes to read. After reading a line the method checks whether the total number of bytes read exceeds the specified number or not. If exceeds the method stops reading the next line.

#read the file
MyFile = open("test.txt", "r")
#read content from the file
print(MyFile.readlines(5))
MyFile.close()

The output of the above code will be:

['This is a test file.\n']

❮ Python File Handling Methods