The way to Learn Particular Strains From a File in Python


If you might want to learn a selected line from a file utilizing Python, then you should utilize one of many following choices:

Choice 1 – Utilizing fileobject.readlines()

If you might want to learn line 10:

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

If you might want to learn traces 10, to twenty:

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

Choice 2 – Utilizing for in fileobject

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

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

print(knowledge)

Choice 3 – Utilizing linecache module

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

Choice 4 – Utilizing enumerate

with open("file.txt") as f:
    for i, line in enumerate(f):
        move  # course of line i
See also  Easy methods to Convert Hex to Byte in Python

Leave a Reply