Created
December 4, 2019 23:13
-
-
Save JosephCatrambone/25476e9a37e932e50c527fc41e164e07 to your computer and use it in GitHub Desktop.
A simple file wrapper to allow seeking to specific lines at random.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LineSeekableFile: | |
def __init__(self, seekable): | |
self.fin = seekable | |
self.line_map = list() # Map from line index -> file position. | |
self.line_map.append(0) | |
while seekable.readline(): | |
self.line_map.append(seekable.tell()) | |
def __getitem__(self, index): | |
# NOTE: This assumes that you're not reading the file sequentially. For that, just use 'for line in file'. | |
self.fin.seek(self.line_map[index]) | |
return self.fin.readline() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment