Skip to content

Instantly share code, notes, and snippets.

@chairco
Created August 15, 2019 00:33
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 chairco/d9b92552ff6beeba4f9bcb59977a8552 to your computer and use it in GitHub Desktop.
Save chairco/d9b92552ff6beeba4f9bcb59977a8552 to your computer and use it in GitHub Desktop.
yield 讀取檔案
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