How do we use file.readlines() to read multiple lines using Python?


The read function reads the whole file at once. You can use the readlines function to read the file line by line.

Example

You can use the following to read the file line by line:

f = open('my_file.txt', 'r+')
for line in f.readlines():
    print line
f.close()

You can also use the with...open statement to open the file and read line by line. For example,

with open('my_file.txt', 'r+') as f:
    for line in f.readlines():
        print line

Updated on: 12-Dec-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements