How to Read Specific Lines From a File in Python

0 min read 126 words

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:

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

If you need to read lines 10, to 20:

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

Option 2 – Using for in fileobject

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

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

Option 4 – Using enumerate

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

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags