Last active
October 24, 2020 09:48
-
-
Save joocer/262cb1db0dd1164d193f8605fced50a8 to your computer and use it in GitHub Desktop.
read an arbitrary long file in python, line by line
This file contains hidden or 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
def read_file(filename, chunk_size=1024*1024, delimiter='\n'): | |
with open(filename, 'r', encoding="utf8") as f: | |
carry_forward = '' | |
chunk = 'INITIALIZED' | |
while len(chunk) > 0: | |
chunk = f.read(chunk_size) | |
augmented_chunk = carry_forward + chunk | |
lines = augmented_chunk.split(delimiter) | |
carry_forward = lines.pop() | |
yield from lines | |
if carry_forward: | |
yield carry_forward |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment