I\'m using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?
Thanks
Reading files is incredible fast. Reading a 100MB file takes less than 0.1 seconds (see my article Reading and Writing Files with Python). Hence you should read it completely and then work with the single lines.
What most answer here do is not wrong, but bad style. Opening files should always be done with with as it makes sure that the file is closed again.
So you should do it like this:
with open("path/to/file.txt") as f:
lines = f.readlines()
print(lines[26]) # or whatever you want to do with this line
print(lines[30]) # or whatever you want to do with this line
If you happen to have a huge file and memory consumption is a concern, you can process it line by line:
with open("path/to/file.txt") as f:
for i, line in enumerate(f):
pass # process line i