File operations are crucial during various tasks. In this article, we will discuss how we can read a file line by line in python.
Read File Using the readline() Method
Python provides us with the readline()
method to read a file. To read the file, we will first open the file using the open()
function in the read mode. The open()
function takes the file name as the first input argument and the literal “r” as the second input argument to denote that the file is opened in the read mode. After execution, it returns a file object containing the file.
After getting the file object, we can use the readline()
method to read the file. The readline()
method, when invoked on a file object, returns the current unread line in the file and moves the iterator to next line in the file.
To read the file line by line, we will read the each line in the file using the readline()
method and print it in a while loop. Once the readline()
method reaches the end of the file, it returns an empty string. Hence, in the while loop, we will also check if the content read from the file is an empty string or not,if yes, we will break out from the for loop.
The python program to read the file using the readline()
method is follows.
myFile = open('sample.txt', 'r')
print("The content of the file is:")
while True:
text = myFile.readline()
if text == "":
break
print(text, end="")
myFile.close()
Output:
The content of the file is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
Suggested Article: Upload File to SFTP Server using C# | DotNet Core | SSH.NET
Read File Line by Line in Python Using the readlines() Method
Instead of the readline()
method, we can use the readlines()
method to read a file in python. The readlines()
method, when invoked on a file object, returns a list of strings, where each element in the list is a line from the file.
After opening the file, we can use the readlines()
method to get a list of all the lines in the file. After that, we can use a for loop to print all the lines in the file one by one as follows.
myFile = open('sample.txt', 'r')
print("The content of the file is:")
lines = myFile.readlines()
for text in lines:
print(text, end="")
myFile.close()
Output:
The content of the file is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
Conclusion
In this article, we have discussed two ways to read a file line by line in python. To learn more about programming in python, you can read this article on list comprehension in Python. You might also like this article on dictionary comprehension in python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.