Created
August 15, 2019 00:33
-
-
Save chairco/d9b92552ff6beeba4f9bcb59977a8552 to your computer and use it in GitHub Desktop.
yield 讀取檔案
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
def chunk(f, newline): | |
buf = "" | |
while True: | |
while newline in buf: | |
pos = buf.index(newline) | |
yield buf[:pos] | |
buf = buf[pos + len(newline):] | |
chunk = f.read(1024) | |
if not chunk: | |
yield buf | |
break | |
buf += chunk | |
with open("log", 'r') as f: | |
for idx, line in enumerate(chunk(f, '\n')): | |
print(f"{idx}: {line}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment