3 solutions
- Use
fileobject.readlines()orfor line in fileobjectas a quick solution for small files.
- Use
linecachefor a more elegant solution, which will be quite fast for reading many files, possible repeatedly.
- Take @Alok's advice and use
enumerate()for files which could be very large, and won't fit into memory. Note that using this method might slow because the file is read sequentially.
How to read specific lines from a file (by line number)?
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?
https://stackoverflow.com/questions/2081836/how-to-read-specific-lines-from-a-file-by-line-number/2081880#2081880

Seonglae Cho