How to read complete text file line by line 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

https://www.codespeedy.com/read-a-specific-line-from-a-text-file-in-python/

raja
Published on 22-Dec-2017 16:02:56
Advertisements