Methods to Learn Particular Traces From a File in Python

If that you must learn a selected line from a file utilizing Python, then you should use one of many following choices:

Possibility 1 – Utilizing fileobject.readlines()#

If that you must learn line 10:

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

If that you must 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):
        go  # course of line i