Python - File readline() Method
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. |
Return Value
Returns the line read from the 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") #Assuming the file contains #This is line 1 content. #This is line 2 content. #This is line 3 content. #read and display first line print(MyFile.readline()) #read and display second line print(MyFile.readline())
The output of the above code will be:
This is line 1 content. This is line 2 content.
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") #Assuming the file contains #This is line 1 content. #This is line 2 content. #This is line 3 content. for line in MyFile: print(line)
The output of the above code will be:
This is line 1 content. This is line 2 content. This is line 3 content.
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") #Assuming the file contains #This is line 1 content. #This is line 2 content. #This is line 3 content. line = MyFile.readline() while line: print(line) line = MyFile.readline()
The output of the above code will be:
This is line 1 content. This is line 2 content. This is line 3 content.
❮ Python File Handling Methods