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

PythonServer Side ProgrammingProgramming

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
raja
Published on 22-Dec-2017 16:13:56
Advertisements