← Previous Module 7: File Handling & Error Handling Next →
Statement
Solution

Python Exercise 7.2: Log Reader

Log files are a common source of data in real-world applications. Write a program that reads a log file called server.log and counts how many lines contain the word "ERROR".

Your program should:

  • Create a file named server.log and write several lines to it, some containing the word ERROR and some that don't.
  • Open and read the file line by line.
  • Count the number of lines that contain the word "ERROR".
  • Print the total count of error lines found.
  • Use a try/except block to handle the case where the file does not exist (FileNotFoundError).

Sample Interaction:

Input
Output
(None)
Reading server.log... Total ERROR lines found: 3

Solution

We first write the log file, then open it for reading and scan each line for the keyword "ERROR", keeping a running counter.

# 1. Create a sample server.log file log_content = """INFO: Server started successfully INFO: Connection established from 192.168.1.1 ERROR: Disk space running low INFO: Request processed in 120ms ERROR: Database connection timeout WARNING: Memory usage above 80% ERROR: Failed to authenticate user INFO: Backup completed successfully """ with open("server.log", "w") as f: f.write(log_content) # 2. Read the file and count ERROR lines try: error_count = 0 print("Reading server.log...") with open("server.log", "r") as f: for line in f: if "ERROR" in line: error_count += 1 print(f"Total ERROR lines found: {error_count}") except FileNotFoundError: print("Error: server.log file not found.")

Key Concepts:

  • open("file", "r") opens a file for reading; "w" opens it for writing.
  • The with statement automatically closes the file when the block exits.
  • Iterating over a file object reads it line by line.
  • "ERROR" in line checks if the substring exists anywhere in the line.
  • FileNotFoundError is raised when Python cannot locate the specified file.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top