Read Text File Line by Line in Python
Hi Dev,
I am going to show you example of read text file line by line in python. if you want to see example of python program to read text file line by line then you are a right place. this example will help you how to read text file line by line in python. I explained simply step by step python read text file line by line into string.
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.
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 nicesnippets.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 nicesnippets.com!
This is body
Thank you
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?