Tuesday, 21 September 2021

Python: Read specific line from a text file

By reading the file line-by-line, we can read specific line from a text file.

 

myfile.txt 

Test line 1
Test line 2
Test line 3
Test line 4
Test line 5
Test line 6

read_specific_line.py

import os

def get_specific_line(file_path, line_number):
    count = 0
    
    with open(file_path) as fp:
        for line in fp:
            count += 1
            if(count == line_number):
                return line

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

print(get_specific_line(path, 2).strip())
print(get_specific_line(path, 20))


Output

Test line 2
None

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment