Tuesday, 21 September 2021

Python: Read specific lines in a 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_lines.py

def get_specific_lines(file_path, line_numbers):
    count = 0

    result = dict()
    
    with open(file_path) as fp:
        for line in fp:
            count += 1
            if(count in line_numbers):
                result[count] = line.strip()
    return result

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

print(get_specific_lines(path, [2, 4, 5]))

 

Output

{2: 'Test line 2', 4: 'Test line 4', 5: 'Test line 5'}

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment