Tuesday 21 September 2021

Python: Read the file content line by line

Using ‘fp.readline()’ method, we can read the contents of file line-by-line.

 

myfile.txt 

Test line 1
Test line 2

 

read_line_by_line.py

import os

file_to_read = 'myfile.txt'
path = '/Users/Shared/data'

with open(os.path.join(path, file_to_read), 'r') as fp:
    while True:
        line = fp.readline()

        if not line:
            break

        print("{}".format(line.strip()))

 

Output

Test line 1
Test line 2

 

You can even use ‘for’ loop to iterate over the file line-by-line.

 

Example

for line in fp:
    print("{}".format(line.strip()))

 

Find the below working application.

 

read_line_by_line_using_for_loop.py

import os

file_to_read = 'myfile.txt'
path = '/Users/Shared/data'

with open(os.path.join(path, file_to_read), 'r') as fp:
    for line in fp:
        print("{}".format(line.strip()))

Output

Test line 1
Test line 2


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment