Python Practice: Build a Log File Analyzer and a File Organizer
Two small jobs that need several tools at once: a log analyzer that parses lines with regex, skips corrupted ones with a custom exception and saves a JSON report, and a file organizer driven by a categories dictionary that logs every move and never overwrites.
What you will learn
- Combine regex, custom exceptions, Counter, logging and JSON in one log analyzer
- Build a config-driven file organizer with pathlib that never overwrites a file
- Prompt an AI tool with Role, Context, Task and Format, then check the output against each requirement
- Add small pytest checks that guard the parts most likely to break
Before you start
- Custom exceptions and logging
- Regular expressions and pathlib
- pytest basics
In this section you learned one tool at a time: exceptions, files, logging, regex and pytest. A real job needs several of them at once. Here are two small use cases that use them together, a log file analyzer and a file organizer.
Think about a small post office. A full bag of letters arrives in the morning. Someone takes them out one at a time, reads each label and drops it in the right pigeonhole. A torn letter with no address turns up; they don't close the post office, they put it aside and make a note. At the end of the day they count each pigeonhole and write a one-page summary. That's both use cases: read one at a time, sort it, set the bad ones aside, then report.
How we work on each one
- Write a prompt with the four parts: role, context, task and format.
- Get code back. It won't be the same for everyone, so what you see here is one possible result.
- Run it on made-up sample data in a temp folder, never on anything important.
- Read the output against what you asked for, one requirement at a time.
- If something's missing, fix the prompt or the code, and go round again.
An AI tool writes fast, but you decide when it's done.
Use case 1: a log file analyzer
Most programs keep writing lines into a log file, and nobody wants to read thousands of them by hand. Each line has a time, a level and a message, and sometimes a line is corrupted. We want four things: count each level, skip corrupted lines, find the most common errors, and save a JSON report. Here's the prompt (take the idea rather than copying it):
Role: You are a Python developer who keeps code
simple and easy to read.
Context: I have a text log file. Each line looks like
"10:15:32 ERROR DB connection timeout". Some lines
are corrupted and have no time or level.
Task: Write a script that reads the file line by
line, counts each level, skips the corrupted lines
and finds the most common error messages.
Format: Two files, log_tools.py for the parsing and
analyze_logs.py for the report. Print a short summary
and save report.json. Standard library only.
If you're stuck, tell an AI tool what you expect and ask it to draft a prompt for you; then read it and change it until it says what you mean. For test data, a small script writes 13 made-up log lines with times 10:15:00 onward and inserts one CORRUPTED_LINE_NO_TIME at index 6, so it becomes line 7. It prints Wrote 14 lines to app.log.
Parsing one line
import re
class LogParseError(Exception):
pass
PATTERN = re.compile(
r"(?P<time>\d{2}:\d{2}:\d{2}) "
r"(?P<level>INFO|WARNING|ERROR|DEBUG) "
r"(?P<message>.+)"
)
def parse_line(line):
match = PATTERN.match(line.strip())
if match is None:
raise LogParseError(f"Bad line: {line.strip()}")
return match.groupdict()
Three named groups, and groupdict() hands them back as a dictionary. On the corrupted line there's no match, so we raise our own custom exception. This file has one job: turn a line into a dictionary, or complain.
The report
import json
import logging
import sys
from collections import Counter
from datetime import datetime
from pathlib import Path
from log_tools import LogParseError, parse_line
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format="%(levelname)s - %(message)s",
)
levels = Counter()
errors = Counter()
bad_lines = 0
total = 0
with open("app.log") as f:
for number, line in enumerate(f, 1):
total += 1
try:
entry = parse_line(line)
except LogParseError:
bad_lines += 1
logging.warning("Line %s skipped", number)
continue
levels[entry["level"]] += 1
if entry["level"] == "ERROR":
errors[entry["message"]] += 1
report = {
"total_lines": total,
"level_counts": dict(levels),
"parse_errors": bad_lines,
"top_errors": errors.most_common(3),
"generated_at": datetime.now().isoformat(
timespec="seconds"
),
}
text = json.dumps(report, indent=2)
Path("report.json").write_text(text)
print("Total lines:", total)
for level, count in sorted(levels.items()):
print(f" {level}: {count}")
print("Parse errors:", bad_lines)
print("Top errors:")
for rank, (message, count) in enumerate(
errors.most_common(3), 1
):
print(f" {rank}. {message} ({count})")
print("Report saved to report.json")
WARNING - Line 7 skipped
Total lines: 14
DEBUG: 2
ERROR: 5
INFO: 4
WARNING: 2
Parse errors: 1
Top errors:
1. DB connection timeout (3)
2. Authentication failed (2)
Report saved to report.json
A Counter is a dictionary made for counting; a missing key starts at zero. enumerate(f, 1) gives the line number. On line 7, parse_line raises, the except catches it, logging prints a warning, and continue moves on. most_common(3) asked for three, but there are only two kinds of error, so we get two. report.json holds the same numbers plus a generated_at timestamp, so another program can read it.
Read it against what you asked for
- Count each level: DEBUG 2, ERROR 5, INFO 4, WARNING 2.
- Skip corrupted lines: one parse error, line 7, the one we planted. 13 counted plus 1 skipped is 14.
- Top errors: we planted three timeouts and two authentication failures. Report saved: yes.
Now try a case the prompt never mentioned. In a fresh folder with no log:
Traceback (most recent call last):
File "S04L06_Practice\analyze_logs.py", line 21, in <module>
with open("app.log") as f:
~~~~^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'app.log'
The code did what we asked, but we never asked about that. That's one more line for the prompt: "say clearly if the file is missing".
Two quick pytest checks
import pytest
from log_tools import LogParseError, parse_line
def test_good_line():
line = "10:15:32 ERROR DB connection timeout"
entry = parse_line(line)
assert entry["level"] == "ERROR"
assert entry["message"] == "DB connection timeout"
def test_bad_line():
with pytest.raises(LogParseError):
parse_line("CORRUPTED_LINE_NO_TIME")
pytest test_log_tools.py gives 2 passed. If anyone changes the pattern later, or an AI tool rewrites it, these tell you straight away if it broke. More on that in testing with pytest.
Use case 2: a file organizer
Think of a downloads folder with photos, reports and code all mixed up, some in subfolders. A helper script makes that mess: 14 small made-up files in a folder called inbox. The rules for where a file goes are kept as data:
from pathlib import Path
CATEGORIES = {
"images": {".jpg", ".jpeg", ".png"},
"docs": {".pdf", ".txt", ".md", ".docx"},
"code": {".py", ".js"},
"data": {".csv", ".json", ".xml"},
}
def category_for(path):
suffix = Path(path).suffix.lower()
for name, suffixes in CATEGORIES.items():
if suffix in suffixes:
return name
return "other"
.jpg finds images; mystery.dat finds nothing and falls through to "other". Want a new category? Add one line to the dictionary; the function doesn't change. That's called config driven.
The prompt has the same four parts. Its context warns that some files share a name, and its task says "never overwrite a file", the kind of detail that's easy to forget. You also don't have to ask for everything at once. Prompt in small steps: first list every file including subfolders; then sort them into categories and print a summary; then move them, never overwriting. Each step gives you something to check before you ask for more.
Step two: a report that moves nothing
The middle step uses rglob("*") to walk every folder under inbox and a defaultdict(list) so a new category starts as an empty list. Its summary:
Summary
code: 2
data: 3
docs: 5
images: 3
other: 1
total: 14
That's the same 14 we created, and it then lists every file under its category, so you can look before anything moves.
Step three: move, log, never overwrite
import logging
import sys
from pathlib import Path
from organizer_tools import category_for
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format="%(levelname)s - %(message)s",
)
moved = 0
for path in sorted(Path("inbox").rglob("*")):
if not path.is_file():
continue
folder = Path("sorted") / category_for(path)
folder.mkdir(parents=True, exist_ok=True)
target = folder / path.name
if target.exists():
logging.warning(
"Skipped %s: name already in %s",
path.as_posix(), folder.name,
)
continue
path.rename(target)
moved += 1
logging.info("%s -> %s", path.name, folder.name)
print("Moved:", moved)
INFO - app.js -> code
INFO - config.json -> data
INFO - script.py -> code
INFO - stock.csv -> data
INFO - mystery.dat -> other
INFO - notes.txt -> docs
INFO - photo.jpg -> images
INFO - logo.png -> images
INFO - trip.jpeg -> images
INFO - sales.csv -> data
INFO - invoice.docx -> docs
WARNING - Skipped inbox/work/notes.txt: name already in docs
INFO - readme.md -> docs
INFO - report.pdf -> docs
Moved: 13
Moving isn't like printing, so try it on made-up files first, never on your only copy. path.rename moves the file and logging writes a line for it. inbox/notes.txt goes to docs first; when work/notes.txt arrives with the same name, target.exists() is true, so we log a warning and skip it.
Against the prompt: every file found (14), 13 sorted, 13 moved plus 1 skipped is 14, both notes files still exist, every move logged. But here's something the output can't decide for you: should the second notes file stay behind? That's your call, and maybe your next prompt asks to rename it instead. A parametrized test with five file names, including PHOTO.JPG in capitals, gives 5 passed.
How this section's tools fit together
| Post office step | Tool |
|---|---|
| Bring the data in | file handling, pathlib and context managers |
| Read each label | regex |
| Set the bad ones aside | exceptions |
| Fill the pigeonholes | Counter, defaultdict |
| Write the summary | JSON or CSV |
| Watch over it all | logging and pytest |
Four challenges
- A config file validator: check the values in an INI or JSON config with regex and your own exceptions, log the errors, count them with
Counterand report as JSON. - A student grade analyzer: read a grades CSV, validate the scores, work out averages with the
mathmodule, and write a JSON report with a timestamp. - A contact book: keep contacts in JSON, validate emails and phone numbers with regex, log every change, and use a
dequefor recently viewed. - An expense tracker: read expense CSVs line by line, parse dates with
datetime, and add up spending per category, grouped by month.
Pick one and write one prompt yourself, with role, context, task and format, without copying these. Then read what comes back against every requirement.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Set Up a Python AI Project with uv, VS Code and an API Key in .env
One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.
uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.
Python try and except Basics: Catch an Error and Keep Going
An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.
Read and Write a File in Python: open, with, Modes and Encoding
Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.
