How to Read Text File Line by Line in Python?
Hey Friends,
In this guide, we are going to learn python read text file line by line. you will learn python read text file line by line and store in array. If you have a question about python read text file line by line into string then I will give a simple example with a solution. letΓ’β¬β’s discuss about how to read text file line by line in python.
I will give you two ways to read text file line by line using readlines() and using for loop. You will be able to get the fastest way to read files line by line in python.
Without any further ado, let's see the below code examples one by one.
You can use these examples with python3 (Python 3) version.
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 ItSolutionstuff.com!\n', 'This is body\n', 'Thank you']
Example 2: using For Loop(Large File)
main.py
# Python read text file using for loop with open('readme.txt') as f: for line in f: print(line.rstrip())
Output:
Hi ItSolutionstuff.com! This is body Thank you
I hope it can help you...