Skip to content

How to Read Specific Lines From a File in Python

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)
Code language: Python (python)

If you need to read lines 10, to 20:

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

Option 2 – Using for in fileobject

lines =[10, 20] data = [] i = with open("file.txt", "r+") as f: for line in f: if i in lines: data.append(line.strip) i = i + 1 print(data)
Code language: Python (python)

Option 3 – Using linecache module

import linecache data = linecache.getline('file.txt', 10).strip()
Code language: Python (python)

Option 4 – Using enumerate

with open("file.txt") as f: for i, line in enumerate(f): pass # process line i
Code language: Python (python)

See also  How to package a Python app (pip) for PyPi
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x