Software Engineering

Find out how to Learn Particular Strains From a File in Python

Find out how to Learn Particular Strains From a File in Python
Written by admin


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

Possibility 1 – Utilizing fileobject.readlines()

If it is advisable learn line 10:

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

If it is advisable learn traces 10, to twenty:

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

Possibility 2 – Utilizing for in fileobject

traces =[10, 20]
information = []
i = 0

with open("file.txt", "r+") as f:
    for line in f:
        if i in traces:
            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

About the author

admin

Leave a Comment