Skip to content
Visual explainer 3h to learn 4 steps

Automating everyday tasks

Write a script that renames, sorts or reports on files in a folder.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 32 of 34

In short

Automation means letting a script do a boring, repeatable task: renaming files, sorting downloads, or building a weekly report. Start with a dry run that only prints what would happen, then let it act.

Explained simply

Automation means writing a small program to do a boring job for you. If you rename 200 photos, sort your Downloads folder every week, or copy numbers into the same report every Monday, a script can do it in seconds and never gets tired or careless.

The best tasks to automate happen often, follow clear rules, and take real time or cause mistakes when done by hand. If you cannot write the rules down in a few sentences, the task is probably not ready for a script yet.

Scripts that move or rename files can also make a mess very quickly. That is why every good automation script starts in dry-run mode: it prints what it would do and changes nothing. You read the list, and only then let it act.

When the script runs, it should tell you what happened: how many files it moved, which ones it skipped and why. Once you trust it, you can even schedule it to run by itself every day or week.

Press Play on a diagram to walk through it one step at a time.

FlowA safe file-sorting script
  1. 1
    Scan the folder

    Path.iterdir() lists every entry

  2. 2
    Decide per file

    Pick a target folder from the suffix

  3. 3
    Dry run

    Print planned moves, change nothing

  4. 4
    Act

    Create folders, move or rename files

  5. 5
    Report

    Summarise counts per category

CycleGrowing a script you can trust
  1. 1
    Write the rules

    Plain sentences and edge cases

  2. 2
    Report only

    Count and list, change nothing

  3. 3
    Dry run

    Print planned actions

  4. 4
    Act with a log

    Every change recorded

  5. 5
    Review and refine

    Fix rules from what you see

  6. Back to step 1

In depth

Picking a task worth automating

A useful rule of thumb: multiply how often you do a task by how long it takes, and compare that with the time to write and test a script. Renaming 50 files once may not be worth it; sorting a folder every day for a year certainly is. Time is not the only gain. Scripts also remove mistakes, such as a typo in a file name or a forgotten step.

Before coding, write the rules as plain sentences: "Every .pdf goes to docs. Files older than 30 days go to archive. Never touch files starting with a dot." Then list the edge cases: two files with the same name, files with no extension, upper-case extensions like .JPG, and files that are still being downloaded. If an action cannot easily be undone, such as deleting, plan a safety net first: move to a trash folder instead, or keep a log of every change.

  • Good: repeated, rule-based, tedious, error-prone
  • Bad: rare, needs human judgement, rules keep changing
  • Start with the read-only part: a report, then add actions

Listing and inspecting files with pathlib

Path("~/Downloads").expanduser() turns ~ into your home folder. folder.iterdir() yields every entry directly inside a folder, in no guaranteed order, so call sorted() when order matters. folder.glob("*.pdf") matches a pattern in one folder, and folder.rglob("*.pdf") searches all subfolders too. Python 3.12 added Path.walk(), similar to os.walk, for full control over walking a tree.

Each Path tells you a lot without opening the file: p.name ("report.final.pdf"), p.stem ("report.final"), p.suffix (".pdf"), p.suffixes ([".final", ".pdf"]) and p.parent. p.is_file() and p.is_dir() filter entries. p.stat() gives st_size in bytes and st_mtime, the last modification time as a timestamp, which datetime.fromtimestamp() turns into a date. Use p.suffix.lower() so .JPG and .jpg are treated the same.

  • sorted(folder.glob("*.csv"), key=lambda p: p.stat().st_mtime)
  • p.with_suffix(".txt") and p.with_name("new.pdf") build new paths
  • Skip hidden files: if p.name.startswith("."): continue

Renaming and moving without losing files

Path.rename(target) behaves differently by operating system. On Linux and macOS it silently replaces an existing file at target; on Windows it raises FileExistsError. Path.replace(target) always overwrites. shutil.move(src, dst) also works across disks (it copies then deletes) and, when dst is an existing folder, moves the file inside it. None of these protect you, so check dest.exists() yourself and pick a free name, like photo (1).jpg.

Batch renames have a subtle trap: renaming a to b and b to c in the wrong order destroys a file. Plan the full list of (old, new) pairs first, check that every new name is unique and does not already exist, and only then act. Write each completed move to a log file (a CSV of old and new paths), so you can undo the whole run with a ten-line script if something looks wrong.

FlowA safe batch rename
  1. 1
    Plan all moves

    Build a list of (old, new) paths

  2. 2
    Check clashes

    New names unique and free

  3. 3
    Dry run

    Print the plan, change nothing

  4. 4
    Act and log

    Move, write old,new to a CSV

  5. 5
    Undo if needed

    Replay the log in reverse

Sorting into folders and generating a report

Sorting is a mapping from a file to a target folder. A dict from suffix to folder name is simplest and easy to change. For broader groups, mimetypes.guess_type(p.name) returns a type like ("image/jpeg", None), so you can sort by the part before the slash. You can also sort by date: build a folder name like 2026/03 from st_mtime. Create targets with dest.mkdir(parents=True, exist_ok=True), which is safe to run every time.

While looping, collect facts for a report: a Counter of files per category, total bytes per folder, and a list of skipped files with reasons. At the end print a short summary, or write it to a CSV or text file with today's date in the name. A run that ends with "Moved 42 files, skipped 3 (name clash)" builds the trust you need before scheduling it.

Running it on a schedule

Once the script is reliable, let the computer start it. On Linux and macOS, cron runs commands on a timetable: crontab -e opens your list, and the line 0 9 * * 1 /home/me/venv/bin/python /home/me/sort_downloads.py runs it at 09:00 every Monday. The five fields are minute, hour, day of month, month and day of week. On Linux, a systemd timer is a modern alternative with better logging. On Windows, use Task Scheduler.

Scheduled jobs run without your terminal, so they behave differently. Use absolute paths for Python, the script and every folder, because cron starts with a minimal environment and a different working directory. Redirect output to a log (>> /home/me/sort.log 2>&1) so you can see what happened. Make the script idempotent: running it twice should do no harm, because the second run finds nothing left to move.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Pick a repetitive task to automate~45m
  2. 2
    List and rename files in bulk~45m
  3. 3
    Sort files into folders by type~45m
  4. 4
    Generate a summary report~45m

Key points

  • Good automation targets tasks you repeat often with clear rules.
  • Always add a --dry-run mode before moving or deleting anything.
  • Use Path.suffix, Path.stem and Path.rename or shutil.move.
  • Never overwrite silently: check if the target already exists.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
import shutil
from pathlib import Path

TYPES = {".jpg": "images", ".png": "images", ".pdf": "docs", ".csv": "data"}

def sort_folder(folder: Path, dry_run: bool = True) -> None:
    for p in folder.iterdir():
        target = TYPES.get(p.suffix.lower())
        if not p.is_file() or target is None:
            continue
        dest = folder / target / p.name
        print(f"{p.name} -> {target}/")
        if not dry_run and not dest.exists():
            dest.parent.mkdir(exist_ok=True)
            shutil.move(p, dest)

Run with dry_run=True first, check the printout, then pass False.

Rename photos by date taken, with clash handling

A folder holds IMG_4831.JPG and similar names. Goal: 2026-03-14_001.jpg style names ordered by modification time. Step 1: sort files by st_mtime. Step 2: build the new name from the date plus a counter. Step 3: skip if the new name already exists. Step 4: only rename when --apply is passed; otherwise print the plan.

python
import sys
from datetime import datetime
from pathlib import Path

folder, apply = Path(sys.argv[1]), "--apply" in sys.argv
photos = sorted((p for p in folder.iterdir() if p.suffix.lower() in {".jpg", ".jpeg"}),
                key=lambda p: p.stat().st_mtime)
for i, p in enumerate(photos, start=1):
    day = datetime.fromtimestamp(p.stat().st_mtime).strftime("%Y-%m-%d")
    new = p.with_name(f"{day}_{i:03}.jpg")
    if new.exists():
        print(f"skip {p.name}: {new.name} exists"); continue
    print(f"{p.name} -> {new.name}")
    if apply:
        p.rename(new)

A weekly folder report as CSV

You want to know what fills a shared folder. Step 1: walk it with rglob("*") and keep only files. Step 2: add each file's size to a total per extension and count files with a Counter. Step 3: write report-YYYY-MM-DD.csv sorted by size. Step 4: schedule it with cron for Monday mornings.

python
import csv
from collections import Counter
from datetime import date
from pathlib import Path
count, size = Counter(), Counter()
for p in Path("/srv/shared").rglob("*"):
    if p.is_file():
        ext = p.suffix.lower() or "(none)"
        count[ext] += 1
        size[ext] += p.stat().st_size
with open(f"report-{date.today()}.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(["extension", "files", "megabytes"])
    for ext, b in size.most_common():
        w.writerow([ext, count[ext], round(b / 1_000_000, 1)])

Quick reference

  • Path("~/Downloads").expanduser().iterdir() lists a folder
  • folder.glob("*.pdf") one level; folder.rglob("*.pdf") all subfolders
  • p.stem, p.suffix.lower(), p.stat().st_size, p.stat().st_mtime
  • dest.mkdir(parents=True, exist_ok=True) is safe to run every time
  • Path.rename silently overwrites on Linux and macOS; check dest.exists() first
  • shutil.move(src, dst) works across disks; shutil.copy2 keeps timestamps
  • cron: minute hour day-of-month month day-of-week, e.g. 0 9 * * 1
  • Use absolute paths and log to a file in scheduled jobs

Common mistakes

  • Running a destructive script on real files without a dry run or backup.
  • Hard-coding absolute paths that only exist on your machine.
  • Not handling name clashes when two files map to the same destination.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1On Linux, what does Path("a.txt").rename("b.txt") do if b.txt already exists?

Question 2

2Which call finds .log files in a folder and all its subfolders?

Question 3

3A script works in your terminal but fails under cron with file not found. The most likely cause?

Question 4

4What does it mean that an automation script is idempotent?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print every file in a folder with its size in kilobytes, largest first.

  2. Exercise 2medium

    Move files older than 30 days from a folder into an archive subfolder, with a dry-run default and a --apply flag.

  3. Exercise 3hard

    Write free_name(dest) that returns dest if it does not exist, otherwise the first free name like report (1).pdf, report (2).pdf.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use os or pathlib for file automation?
Prefer pathlib for new code: paths are objects with readable methods like .suffix and .glob(). Use shutil for copying and moving, and os only for things pathlib does not cover.
How do I undo a script that moved the wrong files?
Only if you planned for it: keep a log of every old and new path, then write a short script that moves each file back. This is why dry runs and logs come before the first real run.
How do I run a Python script automatically every day?
Use cron or a systemd timer on Linux, launchd or cron on macOS, and Task Scheduler on Windows. Point the job at the full path of your virtual environment's python and your script.
Can Python automate tasks in a web browser or Excel too?
Yes. Playwright or Selenium can drive a browser, and openpyxl reads and writes Excel files. Start with file and folder tasks, which need only the standard library.
ShareXLinkedInWhatsApp