Skip to content
TutorialBeginner13 min read

Python Automation with AI Assistance

Build a small Python utility with AI help, then add tests, logging and safe defaults before running it on real files.

AIAI Skills Hub ResearchResearch team Published Apr 9, 2026Updated May 19, 2026 Reviewed May 19, 2026 13 min read

Prerequisites

  • • Python 3.10+ installed
  • • Basic command-line skills
  • • A code editor

What you will learn

  • Turn a repetitive file task into a tested script
  • Use safe defaults such as dry-run mode
  • Review AI-generated code for side effects

Choose a small, reversible task

A good first automation renames files, extracts text, or summarises a CSV. Avoid tasks that delete data or call production APIs. The goal is to build the habit of testing and review.

Describe the contract to the assistant

Prompt:

Write a Python script that:
- takes a directory and a --apply flag
- finds .jpeg files
- proposes renaming them to YYYY-MM-DD-<slug>.jpg based on the file's modified date and current name
- prints every planned rename
- only renames when --apply is passed
- refuses to overwrite an existing file
- logs failures and continues

Use only the standard library. Include a docstring and type hints.

The dry-run default is the most important requirement. It makes the script safe to run before you trust it.

Review the generated code

Check for:

  • path traversal or accidental access outside the target directory,
  • overwrite behaviour,
  • symlink handling,
  • date parsing and timezone assumptions,
  • exceptions that stop the entire run,
  • logging that leaks full paths if they contain sensitive names.
from __future__ import annotations

import argparse
import re
from datetime import datetime
from pathlib import Path


def slugify(value: str) -> str:
    value = re.sub(r"[^a-zA-Z0-9]+", "-", value).strip("-").lower()
    return value[:60] or "file"


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("directory", type=Path)
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()

    root = args.directory.resolve()
    if not root.is_dir():
        raise SystemExit(f"Not a directory: {root}")

    planned = 0
    for source in sorted(root.glob("*.jpeg")):
        stamp = datetime.fromtimestamp(source.stat().st_mtime).strftime("%Y-%m-%d")
        target = source.with_name(f"{stamp}-{slugify(source.stem)}.jpg")
        if target.exists():
            print(f"SKIP exists: {target.name}")
            continue
        print(f"{'RENAME' if args.apply else 'DRY RUN'}: {source.name} -> {target.name}")
        planned += 1
        if args.apply:
            source.rename(target)

    print(f"{planned} file(s) {'renamed' if args.apply else 'would be renamed'}")


if __name__ == "__main__":
    main()

Test on a copy

Create a temporary folder with three files: a normal JPEG, a name with spaces, and a target that already exists. Run without --apply, inspect the output, then run with --apply. Confirm the existing file was not overwritten.

Add logging and a summary

Print a summary at the end: processed, skipped, failed. If you need a persistent log, write a CSV with timestamp, source, target and status. Do not log file contents.

Use AI for the next iteration, not the first

Once the script works, ask the assistant to review it for edge cases. A reviewer with the working code and test results is more useful than a generator working from a vague description.

Exercises

Do these before moving on. Reading is not the same as being able to apply it.

Exercise 1

Add a dry-run flag

Modify the example script to print planned changes and require --apply to write anything.

Exercise 2

Add a failure log

Write failed filenames to a CSV with the error reason instead of stopping the whole run.

References

Finished this tutorial? Continue with a guided path.

Browse learning paths →

Related resources