Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

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

  1. Write a prompt with the four parts: role, context, task and format.
  2. Get code back. It won't be the same for everyone, so what you see here is one possible result.
  3. Run it on made-up sample data in a temp folder, never on anything important.
  4. Read the output against what you asked for, one requirement at a time.
  5. 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
Log analyzer flow: app.log is read one line at a time, parse_line uses a regex; good lines go to the level and error Counters; a corrupted line raises LogParseError, is logged as a warning and skipped; at the end the counters become report.json and a summary app.log one line at a time parse_line regex groups Counter levels, errors LogParseError warn, skip line 7 report.json + summary continue
Read, sort, set the bad one aside, report. One bad line costs one warning, not the whole job.

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 stepTool
Bring the data infile handling, pathlib and context managers
Read each labelregex
Set the bad ones asideexceptions
Fill the pigeonholesCounter, defaultdict
Write the summaryJSON or CSV
Watch over it alllogging 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 Counter and report as JSON.
  • A student grade analyzer: read a grades CSV, validate the scores, work out averages with the math module, 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 deque for 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.

Keep going in Python · 33 of 48

Previous
Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
Next post
Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • How we work on each one
  • Use case 1: a log file analyzer
  • Parsing one line
  • The report
  • Read it against what you asked for
  • Two quick pytest checks
  • Use case 2: a file organizer
  • Step two: a report that moves nothing
  • Step three: move, log, never overwrite
  • How this section's tools fit together
  • Four challenges
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.