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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Append Text or Lines to a Text File in Python?
- Python Generate Text File from List Example
- Python Create Text File If Not Exists Example
- Python Create Text File in Specific Directory Example
- How to Create Multiline Text File in Python?
- Python Create an Empty Text File Example
- How to Create Text File in Python?
- How to Get Max Value from Python List?
- How to Convert List to Lowercase in Python?
- Python Split String into List of Characters Example
- How to Remove Duplicate Values from List in Python?
- How to Get Current Hour in Python?