Read a large log file (10 GB) and count lines matching a pattern without running out of memory.
BeginnerHands-onPython for DevOps
Answer
count = 0
with open("/var/log/huge.log", "r", errors="replace") as f:
for line in f: # streams line by line
if " 500 " in line:
count += 1
print(count)
Key trick → Iterating the file object streams it. f.read() or readlines() would load all 10 GB into memory. errors="replace" survives stray non-UTF-8 bytes.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate