Python - File readline() Method


Advertisements

The Python file 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 return of the given file.

Syntax


file.readline(size)

Parameters

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

Example: Read multiple lines

If the method is called multiple times, it will read and return multiple lines of the file. In the below example, readline() method is used twice to read first two lines of the file called MyFile.

MyFile = open("python_test.txt", "r")
#read first line of the content
print(MyFile.readline())

#read second line of the content
print(MyFile.readline())

Output

Python is a programming language.

Learning Python is fun.

Loop through the lines of the File

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

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

for line in MyFile:
  print(line)

Output

Python is a programming language.

Learning Python is fun.

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

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

line = MyFile.readline()
while line:
  print(line)
  line = MyFile.readline()

Output

Python is a programming language.

Learning Python is fun.

Python File Handling Methods
Advertisements