Skip to content

Instantly share code, notes, and snippets.

@JosephCatrambone
Created December 4, 2019 23:13
Show Gist options
  • Save JosephCatrambone/25476e9a37e932e50c527fc41e164e07 to your computer and use it in GitHub Desktop.
Save JosephCatrambone/25476e9a37e932e50c527fc41e164e07 to your computer and use it in GitHub Desktop.
A simple file wrapper to allow seeking to specific lines at random.
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