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:

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

If you need to read lines 10, to 20:

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

Option 2 – Using for in fileobject

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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

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

Option 4 – Using enumerate

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