Python Read Text File Line by Line Example

Published On: 27/12/2022 | Category: Python


Hi Guys,

Now, let's see example of python read text file line by line. it's simple example of python read text file line by line into string. let’s discuss about how to read text file line by line in python. We will use python program to read text file line by line. Let's get started with python read text file line by line and store in array.

I'll demonstrate using readlines() and a for loop two different techniques to read text files line by line. The quickest method for reading files line by line in Python will be available to you.

So let's see bellow example:

Example 1: using readlines()

main.py
# Python read text file using readlines()
with open('readme.txt') as f:
    lines = f.readlines()
  
print(lines)
Output
['Hi Tuts-Station.com!\n', 'This is body\n', 'Thank you']

Example 2: using For Loop(Large File)

main.py
with open('readme.txt') as f:
    for line in f:
        print(line.rstrip())
Output
Hi Tuts-Station.com!
This is body
Thank you

It will help you....

Happy Pythonic Coding!