I’m reading specific lines from a text file. Here is my code:
file.seek(0)
for j, ln in enumerate(file):
if j == line_number
line = ln # i'm getting the line
break
It tooks a long time when I use this code in a “loop” where the line_number is random every turn.
I also tried linecache.getline() but it needs to be call linecache.clearcache() every turn, so its not better.
Is there a faster solution for that? Memory doesn’t matter.
If memory truly doesn’t matter:
You read the file in once, store it in memory, and access it from there.
Edit: Where memory matters:
We can use
itertools.dropwhile()to ignore the lines until we get to the one we need.