Home › Interview Questions › How would you read a log file and print only the l…

How would you read a log file and print only the lines that contain error messages?

🟢 Easy Coding Fresher level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

You can read the file line by line and filter for the keyword 'ERROR' (or any pattern that identifies an error). For example, in Python:

with open('app.log', 'r') as f:

for line in f:
    if 'ERROR' in line.upper():
        print(line.rstrip())

This approach streams the file, uses minimal memory, and outputs only the error lines. Adjust the keyword to match your log’s error indicator.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500