Read Text File Line by Line in Python

21-Dec-2022

.

Admin

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

#Python