Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

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.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging