Created
June 2, 2020 15:17
-
-
Save lostella/6eadba7cdbaca99347e3ae728ed34a71 to your computer and use it in GitHub Desktop.
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
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