Python Tutorial Python Advanced Python References Python Libraries

Python - File readline() Method



The Python readline() method is used to read and return one line of the file object. The method has an optional parameter which is used to specify number of bytes to read and returns the read content.

If the method is called multiple times, it will read and return multiple lines of the file.

Syntax

file.readline(size)

Parameters

size Optional. specify number of bytes to read and return. default is -1 which means the whole line.

Return Value

Returns the line read from the file.

Example: Read multiple lines

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, readline() method is used to read first line of the given file. After that, first 11 bytes of second line is read.

#read the file
MyFile = open("test.txt", "r")
#read the first line
print(MyFile.readline(), end="")
#read 11 bytes of second line
print(MyFile.readline(11), end="")
MyFile.close()

The output of the above code will be:

This is a test file.
It contains

Loop through the lines of the File

By using for loop, the whole content of the file can be read line by line.

#read the file
MyFile = open("test.txt", "r")
for line in MyFile:
  print(line, end="")

The output of the above code will be:

This is a test file.
It contains dummy content.

Similarly, the while loop can also be used to read the whole content of the file line by line.

#read the file
MyFile = open("test.txt", "r")
line = MyFile.readline()
while line:
  print(line, end="")
  line = MyFile.readline()

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ Python File Handling Methods