If it’s essential learn a selected line from a file utilizing Python, then you need to use one of many following choices:
Possibility 1 – Utilizing fileobject.readlines()
If it’s essential learn line 10
:
with open("file.txt") as f:
information = f.readlines()[10]
print(information)
If it’s essential learn strains 10, to twenty
:
with open("file.txt") as f:
information = f.readlines()[10:20]
print(information)
Possibility 2 – Utilizing for
in fileobject
strains =[10, 20]
information = []
i = 0
with open("file.txt", "r+") as f:
for line in f:
if i in strains:
information.append(line.strip)
i = i + 1
print(information)
Possibility 3 – Utilizing linecache
module
import linecache
information = linecache.getline('file.txt', 10).strip()
Possibility 4 – Utilizing enumerate
with open("file.txt") as f:
for i, line in enumerate(f):
move # course of line i