Skip to content

Instantly share code, notes, and snippets.

@lostella
Created June 2, 2020 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lostella/6eadba7cdbaca99347e3ae728ed34a71 to your computer and use it in GitHub Desktop.
Save lostella/6eadba7cdbaca99347e3ae728ed34a71 to your computer and use it in GitHub Desktop.
from pathlib import Path
from typing import List
class IndexedFile:
def __init__(self, path: Path) -> None:
self.path = path
self.offset: List[int] = []
self._build_index()
def _build_index(self) -> None:
cumlen = 0
with open(self.path) as fp:
for line in fp:
self.offset.append(cumlen)
cumlen += len(line)
def get_line(self, k: int) -> str:
assert k < len(self.offset)
with open(self.path) as fp:
fp.seek(self.offset[k])
line = fp.readline()
return line
if __name__ == "__main__":
idxfile = IndexedFile(Path("./temp.txt"))
print(idxfile.get_line(3))
print(idxfile.get_line(2))
print(idxfile.get_line(1))
print(idxfile.get_line(0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment