Programming from zero

Extract error lines into a new file

mediumReading and writing files Must-do

Problem statement

Read app.log, find every line whose level is ERROR, and write those lines to a new file errors.log. Print Found N errors and then each error line.

Examples

Example 1

Input: app.log contains: 2026-09-24 10:00:01 INFO service started 2026-09-24 10:02:15 INFO request handled in 120ms 2026-09-24 10:05:42 ERROR database connection refused 2026-09-24 10:06:10 WARNING slow response 2300ms 2026-09-24 10:07:55 ERROR disk full on /var

Output: Found 2 errors 2026-09-24 10:05:42 ERROR database connection refused 2026-09-24 10:07:55 ERROR disk full on /var

Hints

Approach

Optimal

This combines reading, filtering and writing. First read app.log line by line and append every line containing " ERROR " to a list. Checking for the word with spaces around it avoids matching a message like no ERRORS found. Next open errors.log with mode "w" and write the collected lines with writelines(), which writes each string as is; since each line read from a file keeps its trailing newline, the new file ends up one error per line. Finally print the count with len() and each line with .rstrip() to drop the newline before printing.

Python
errors = []
with open("app.log", encoding="utf-8") as f:
for line in f:
if " ERROR " in line:
errors.append(line)
with open("errors.log", "w", encoding="utf-8") as out:
out.writelines(errors)
print(f"Found {len(errors)} errors")
for line in errors:
print(line.rstrip())

Follow-up questions

  • Also include WARNING lines, and print a count for each level.
  • Write only the message part (after the level) to errors.log.

Frequently asked questions

Each line from the file already ends with \n, and print adds another. Call line.rstrip() (or line.strip()) before printing.

Yes, for this simple case. Python becomes worth it when the logic grows: counting per error type, parsing timestamps, or combining several files into one report.