How to Read Specific Lines From a File in Python


If you need to read a specific line from a file using Python, then you can use one of the following options:

Option 1 – Using fileobject.readlines()

If you need to read line 10:

with open("file.txt") as f:
    data = f.readlines()[10]
print(data)

If you need to read lines 10, to 20:

with open("file.txt") as f:
    data = f.readlines()[10:20]
print(data)

Option 2 – Using for in fileobject

lines =[10, 20]
data = []
i = 0

with open("file.txt", "r+") as f:
    for line in f:
        if i in lines:
            data.append(line.strip)
            
        i = i + 1

print(data)

Option 3 – Using linecache module

import linecache
data = linecache.getline('file.txt', 10).strip()

Option 4 – Using enumerate

with open("file.txt") as f:
    for i, line in enumerate(f):
        pass  # process line i