How do you read a huge log file efficiently?
IntermediateConceptExceptions, context managers, files & logging
Answer
Iterate the file object, which reads line by line with buffering, instead of .read() or .readlines() that load everything into memory.
import gzip
from collections import Counter
def lines(path):
opener = gzip.open if path.endswith(".gz") else open
with opener(path, "rt", encoding="utf-8", errors="replace") as f:
yield from f
codes = Counter(l.split()[8] for l in lines("access.log.gz") if len(l.split()) > 8)
errors="replace" keeps one bad byte from killing a multi-GB parse.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?Beginner