π€ Python Automation
in Python
Learn Python automation: organise files, rename in bulk safely, build CSV reports, schedule jobs, log errors and keep unattended scripts safe.
What this lesson is about
Automation is the part of programming that pays you back the fastest. A script that renames two hundred files, sorts a messy downloads folder or builds the weekly report in one second does not need to be clever. It only needs to be correct, and then it never gets tired, never skips a file and never makes a typing mistake.
In this lesson I show you the small set of tools I use for almost every automation job: pathlib for paths, shutil for moving and copying, csv for reports, logging for a record of what happened, and a simple loop for scheduling. Every example here runs in your browser against a temporary folder that disappears afterwards, so you can experiment without any risk to your real files.
The lesson is organised around one idea that matters more than any library: automation should be boring and safe. You will learn to preview what a script will do before it does it, to make it safe to run twice, and to make it leave a trail you can read when something goes wrong at three in the morning.
What you will learn
- βHow to decide whether a task is worth automating
- βBuilding and inspecting paths with
pathlib - βSorting files into folders by extension
- βRenaming many files safely with a dry run
- βWriting and reading CSV reports
- βHow scheduling really works (cron, Task Scheduler, loops)
- βLogging and error handling for unattended scripts
- βIdempotence, backups and other safety habits
Why programmers should learn this
- β Repetitive computer work is the easiest thing to hand to Python, and every hour you save is an hour for harder problems.
- β Automation scripts are small, so they are the best place to practise files, errors, logging and testing in real situations.
- β Almost every job that touches data, operations or support has manual steps that a short script can remove.
- β Writing safe scripts teaches habits (dry runs, backups, logging) that matter in every kind of software.
- β A folder of useful personal scripts is a portfolio that shows you solve real problems, not just exercises.
Is this task worth automating?
Before writing any code I ask three questions. How often will I do this? How long does it take by hand? How long will the script take to write and keep working? A task that takes ten minutes and happens every week is a strong candidate, because it costs more than eight hours a year. A task that happens once and takes five minutes is not.
The calculation is simple enough to turn into a function. Put the numbers in honestly: include the time to test the script and fix it when file names change. Many people overestimate how often they repeat a task and underestimate the cost of maintenance, so I leave a safety margin.
Automation also pays off in ways the formula does not capture. A script does the job the same way every time, so mistakes caused by tiredness disappear, and the steps are written down where a colleague can read them.
There is also a hidden cost to avoid: automating a task nobody needs. Before writing code I check that the output is really used. A report that no one reads is not worth a script, however easy it is to build. I also write the manual steps down first, because a task I cannot describe clearly is a task I cannot yet automate well.
def break_even_weeks(minutes_by_hand, runs_per_week, minutes_to_build, minutes_upkeep_per_month=10):
saved_per_week = minutes_by_hand * runs_per_week
upkeep_per_week = minutes_upkeep_per_month / 4
net = saved_per_week - upkeep_per_week
if net <= 0:
return None
return minutes_to_build / net
for name, by_hand, runs, build in [
("Weekly report", 30, 1, 180),
("Rename photos", 15, 0.25, 90),
("Daily backup check", 5, 5, 120),
]:
weeks = break_even_weeks(by_hand, runs, build)
if weeks is None:
print(f"{name}: never pays back")
else:
print(f"{name}: pays back after {weeks:.1f} weeks")Weekly report: pays back after 6.5 weeks Rename photos: pays back after 72.0 weeks Daily backup check: pays back after 5.3 weeks
Line by line
- 1-7The function works out minutes saved each week, subtracts a small monthly upkeep cost, and returns how many weeks until the build time is repaid. It returns None when the script would never pay back.
- 10-14Three example tasks with minutes by hand, runs per week and minutes to build.
- 15-20Loop over the tasks, call the function and print a readable verdict. The
:.1fformat shows one decimal place.
Round your build estimate up. Scripts almost always take longer than planned because real files are messier than the examples you imagined.
Paths with pathlib
Strings are a poor way to represent file paths, because every operating system writes them differently. pathlib.Path treats a path as an object. You join parts with the / operator, ask for .name, .suffix or .parent, and the same code works on Windows, macOS and Linux.
In this lesson every example creates its own temporary folder with tempfile.TemporaryDirectory(). When the with block ends, the folder and everything in it is deleted. That makes the examples safe to run and shows a pattern worth copying whenever you test file code.
Learn four methods and you can do most jobs: mkdir(parents=True, exist_ok=True) to create folders, write_text() and read_text() for small files, iterdir() to list a folder and glob() or rglob() to search by pattern.
Paths also answer questions without opening files. exists(), is_file() and is_dir() tell you what is there, and stat().st_size gives the size in bytes. Checking first and acting second is a habit that prevents a large share of file errors, such as reading a file that is not there or creating a folder that already exists.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "reports" / "2026").mkdir(parents=True)
(root / "reports" / "2026" / "jan.txt").write_text("January totals")
(root / "reports" / "2026" / "feb.txt").write_text("February totals")
(root / "notes.md").write_text("# Notes")
sample = root / "reports" / "2026" / "jan.txt"
print(sample.name, sample.stem, sample.suffix)
print(sample.parent.name)
print(sorted(p.name for p in root.rglob("*.txt")))
print(sample.read_text())jan.txt jan .txt 2026 ['feb.txt', 'jan.txt'] January totals
Line by line
- 1-2Import
tempfilefor a throw-away folder andPathfor path objects. - 4-5Create a temporary directory and wrap it in a
Path. Everything made inside disappears at the end of the block. - 6-9
mkdir(parents=True)builds nested folders in one call, then three small files are written. - 11-13Show the file name, name without extension, extension and the name of its parent folder.
- 14-15
rglob('*.txt')searches every sub-folder for text files, andread_text()loads one file back.
Prefer Path over string concatenation. root / 'a' / 'b.txt' is easier to read and cannot produce a doubled slash.
Organise files by extension
The classic first automation is tidying a downloads folder. The plan is short: look at every file, work out its category from the extension, create the matching folder and move the file into it.
I keep the decision logic separate from the moving. A small dictionary maps extensions to folder names, and a function returns the destination for any file. Separating the two means I can test the decision without touching a single file.
Notice that the script uses Path.rename() only after the destination folder exists, and that unknown extensions go to an other folder instead of crashing the run.
Real folders are messier than examples. Files may have no extension, names may be upper case, and hidden files may start with a dot. Print a summary of what the script found before you let it move anything, and decide deliberately what should happen to the odd cases. A catch-all folder is a simple answer that keeps the run moving while you decide.
import tempfile
from pathlib import Path
CATEGORIES = {
".jpg": "images", ".png": "images",
".pdf": "documents", ".txt": "documents",
".csv": "data", ".xlsx": "data",
}
def folder_for(path):
return CATEGORIES.get(path.suffix.lower(), "other")
def organise(folder):
moved = []
for item in sorted(folder.iterdir()):
if item.is_file():
target_dir = folder / folder_for(item)
target_dir.mkdir(exist_ok=True)
item.rename(target_dir / item.name)
moved.append((item.name, target_dir.name))
return moved
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for name in ["cat.JPG", "cv.pdf", "sales.csv", "notes.txt", "setup.exe"]:
(root / name).write_text("x")
for name, where in organise(root):
print(f"{name} -> {where}/")
print(sorted(p.name for p in root.iterdir()))cat.JPG -> images/ cv.pdf -> documents/ notes.txt -> documents/ sales.csv -> data/ setup.exe -> other/ ['data', 'documents', 'images', 'other']
Line by line
- 4-8A dictionary maps each known extension to a folder name.
- 11-12
folder_forlower-cases the suffix so.JPGand.jpgmatch, and falls back toother. - 15-22
organiseloops over files, creates the target folder if needed, renames (moves) each file and records what it did. - 25-31Create five sample files, run the function and print every move, then list the folders that now exist.
Moving a file onto an existing name can overwrite it on some systems. In real scripts check target.exists() first and add a number to the name.
Bulk renaming with a dry run
Renaming is where automation can quietly destroy work, so I always build a dry run first. The function computes the plan, a list of old and new names, and prints it. Only when the plan looks right do I call the function again with apply=True.
A good rename plan also checks for collisions. If two files would end up with the same new name, the script should stop and say so instead of overwriting one of them.
The pattern here, plan first and act second, is the most useful safety habit in this lesson. It works for renaming, deleting, uploading and sending emails.
import tempfile
from pathlib import Path
def plan_renames(folder, prefix):
plan = []
files = sorted(p for p in folder.iterdir() if p.is_file())
for number, path in enumerate(files, start=1):
new_name = f"{prefix}_{number:03d}{path.suffix.lower()}"
plan.append((path, folder / new_name))
targets = [new for _, new in plan]
if len(set(targets)) != len(targets):
raise ValueError("two files would get the same name")
return plan
def rename_all(folder, prefix, apply=False):
plan = plan_renames(folder, prefix)
for old, new in plan:
print(("RENAME " if apply else "WOULD RENAME ") + f"{old.name} -> {new.name}")
if apply:
old.rename(new)
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for name in ["IMG_8841.JPG", "IMG_8842.JPG", "holiday.png"]:
(root / name).write_text("x")
rename_all(root, "trip")
print("--- applying ---")
rename_all(root, "trip", apply=True)
print(sorted(p.name for p in root.iterdir()))WOULD RENAME IMG_8841.JPG -> trip_001.jpg WOULD RENAME IMG_8842.JPG -> trip_002.jpg WOULD RENAME holiday.png -> trip_003.png --- applying --- RENAME IMG_8841.JPG -> trip_001.jpg RENAME IMG_8842.JPG -> trip_002.jpg RENAME holiday.png -> trip_003.png ['trip_001.jpg', 'trip_002.jpg', 'trip_003.png']
Line by line
- 5-13
plan_renamesbuilds a list of (old, new) paths using a three-digit counter and the lower-cased suffix. It raises an error if two targets would collide. - 16-21
rename_allprints each step. The word WOULD is shown during a dry run, and the rename only happens whenapply=True. - 24-31Create three files, run a dry run, then apply the plan and list the final names.
CSV reports
Reports are what most automation ends with, and CSV is the simplest format that every spreadsheet understands. The csv module handles quoting and commas inside values, which is exactly where hand-built strings break. A line such as Pen, blue would be split into two columns by a naive join, and the report would be wrong without any error message.
csv.DictWriter writes rows from dictionaries, so the column order is explicit and the code reads like the report. csv.DictReader brings the data back as dictionaries, which makes totals and filters easy.
In the example I write to an in-memory text buffer with io.StringIO, which behaves like a file. In a real script you would pass an open file instead.
import csv
import io
sales = [
{"region": "North", "item": "Notebook", "units": 12, "price": 2.5},
{"region": "South", "item": "Pen, blue", "units": 30, "price": 0.8},
{"region": "North", "item": "Pen, blue", "units": 18, "price": 0.8},
]
buffer = io.StringIO()
writer = csv.DictWriter(buffer, fieldnames=["region", "item", "units", "price", "total"])
writer.writeheader()
for row in sales:
writer.writerow({**row, "total": round(row["units"] * row["price"], 2)})
text = buffer.getvalue()
print(text)
totals = {}
for row in csv.DictReader(io.StringIO(text)):
totals[row["region"]] = totals.get(row["region"], 0) + float(row["total"])
print(totals)region,item,units,price,total
North,Notebook,12,2.5,30.0
South,"Pen, blue",30,0.8,24.0
North,"Pen, blue",18,0.8,14.4
{'North': 44.4, 'South': 24.0}Line by line
- 4-8Sample rows as dictionaries. One item name contains a comma on purpose.
- 10-14
DictWriterneeds the column order. Each row gets a computedtotaladded with dictionary unpacking{**row, ...}. - 16-17
getvalue()returns everything written so far. Note that the comma in 'Pen, blue' is quoted automatically. - 19-22
DictReaderturns each line back into a dictionary. Values come back as text, so convert withfloat()before adding.
Scheduling: how it really works
A schedule is just a rule that starts your script at the right time. On Linux and macOS that rule lives in cron, on Windows it lives in Task Scheduler, and on a hosted service such as GitHub Actions it lives in a workflow file. Python itself does not need to stay open; the operating system starts it.
You can also build a scheduler inside Python with a loop that checks whether a job is due. That is handy for small tools, but a loop dies when the computer sleeps or restarts, so for anything important I let the operating system do the scheduling.
The example below separates the idea from the clock. A Scheduler holds jobs with an interval, and a fake clock that I advance by hand makes the output identical every run, which is also how you would test a real scheduler.
Whatever tool starts the script, a few rules apply. Use absolute paths, because the working directory of a scheduled job is rarely the one you expect. Write a log, because nobody sees the screen. And make sure a slow run cannot overlap the next one, for example by writing a lock file at the start and removing it at the end.
class Scheduler:
def __init__(self):
self.jobs = []
def every(self, minutes, name, action):
self.jobs.append({"every": minutes, "name": name, "action": action, "next": minutes})
def tick(self, now):
for job in self.jobs:
if now >= job["next"]:
job["action"](now)
job["next"] += job["every"]
log = []
scheduler = Scheduler()
scheduler.every(15, "check-site", lambda t: log.append(f"minute {t}: checked the site"))
scheduler.every(60, "backup", lambda t: log.append(f"minute {t}: ran the backup"))
for minute in range(0, 121, 15):
scheduler.tick(minute)
print("\n".join(log))minute 15: checked the site minute 30: checked the site minute 45: checked the site minute 60: checked the site minute 60: ran the backup minute 75: checked the site minute 90: checked the site minute 105: checked the site minute 120: checked the site minute 120: ran the backup
Line by line
- 1-12A tiny scheduler stores each job with its interval and the next minute it should run.
tick(now)runs every job that is due and moves its next time forward. - 15-18Two jobs are registered: one every 15 minutes, one every 60 minutes.
- 20-23The fake clock steps through two hours in 15-minute jumps, so the output is the same every time.
# crontab entries (run: crontab -e) # minute hour day-of-month month day-of-week command 0 8 * * 1 python3 /home/me/scripts/weekly_report.py */15 * * * * python3 /home/me/scripts/check_site.py
Line by line
- 2The five fields are minute, hour, day of month, month and weekday.
- 3Every Monday at 08:00.
- 4
*/15means every fifteen minutes.
Logging and error handling for unattended scripts
When you run a script yourself, you see errors on screen. When it runs at night, nobody is watching, so the script must write down what it did. The logging module gives you timestamps, levels such as INFO and ERROR, and a single place to send them.
Wrap the work for each item in try and except so that one bad file does not stop the other hundred. Log the problem, continue with the next item, and report a summary at the end. A script that fails loudly on the first problem is easier to debug but worse to rely on, so I choose per task. Whichever you pick, finish with a summary line that states how many items succeeded and how many failed, so a quick glance at the log tells you whether the night went well.
The example logs to an in-memory stream so you can see the output here. In real scripts use logging.FileHandler to write to a file, or basicConfig(filename=...) for the simple case.
import io
import logging
stream = io.StringIO()
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
log = logging.getLogger("jobs")
log.setLevel(logging.INFO)
log.addHandler(handler)
def process(value):
return 100 / value
done, failed = 0, 0
for value in [5, 0, 20, "x"]:
try:
result = process(value)
log.info("processed %s -> %s", value, result)
done += 1
except (ZeroDivisionError, TypeError) as error:
log.error("could not process %r: %s", value, error)
failed += 1
log.info("summary: %d done, %d failed", done, failed)
print(stream.getvalue())INFO processed 5 -> 20.0 ERROR could not process 0: division by zero INFO processed 20 -> 5.0 ERROR could not process 'x': unsupported operand type(s) for /: 'int' and 'str' INFO summary: 2 done, 2 failed
Line by line
- 4-9Create a logger whose output goes to an in-memory stream, with a simple format showing the level and message.
- 12-13A function that can fail: dividing by zero or by a string.
- 17-24Each value is processed inside
try. Success is logged at INFO, known errors at ERROR, and the loop continues either way. - 26-27A final summary line, then print everything that was logged.
Safety habits: idempotence, backups and dry runs
A script is idempotent when running it twice gives the same result as running it once. Sorting files into folders is idempotent, because the second run finds nothing to move. Appending a line to a file is not, because the second run adds it again. Idempotent scripts are safe to schedule, safe to restart after a crash and safe to run by mistake.
I keep a short checklist for every script that changes things: preview with a dry run, never delete when moving would do, copy important data first, and write results to a new file instead of overwriting the original. Each step costs a few lines and prevents the kind of mistake that cannot be undone.
The final example shows a backup helper that never overwrites: if a file with the same name exists it adds a number, and it is safe to run again.
Finally, think about secrets and permissions. A script that deletes or uploads things should run with the least access it needs, and passwords belong in environment variables, never in the file. These small habits are what separate a quick hack from a script you can trust to run while you sleep.
import shutil
import tempfile
from pathlib import Path
def safe_copy(source, folder):
folder.mkdir(exist_ok=True)
target = folder / source.name
counter = 1
while target.exists():
target = folder / f"{source.stem}_{counter}{source.suffix}"
counter += 1
shutil.copy2(source, target)
return target
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
original = root / "budget.txt"
original.write_text("v1")
backups = root / "backups"
for _ in range(3):
print(safe_copy(original, backups).name)
print(sorted(p.name for p in backups.iterdir()))budget.txt budget_1.txt budget_2.txt ['budget.txt', 'budget_1.txt', 'budget_2.txt']
Line by line
- 6-14
safe_copycreates the backup folder if needed, then keeps trying new names (budget_1.txt,budget_2.txt) until it finds one that is free.copy2also keeps the file's timestamps. - 17-24Run the helper three times on the same file and show that nothing is overwritten.
Before pointing a script at real data, run it on a copy of the folder. If the result looks right, switch to the original.
Common mistakes
β Running a destructive script without a dry run
Renaming, moving and deleting are hard to undo. Always print the plan first and apply it only when it looks right.
β Building paths with string concatenation
Gluing strings with slashes breaks on other systems and creates doubled separators. Use pathlib.Path and the / operator.
β Letting one bad file stop everything
A single unreadable file should not end a nightly run. Catch the specific errors, log them and continue.
β Assuming the script runs from the folder you expect
A scheduled job often starts in a different working directory. Use absolute paths or build paths from Path(__file__).parent.
β Hard-coding passwords and keys
Never write secrets into a script. Read them from environment variables so they stay out of your files and your repository.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What is the main benefit of a dry run?
Q2. Which expression joins two path parts with pathlib?
Path objects overload / so that root / 'a' joins parts correctly on every operating system.Q3. A script is idempotent when...
Q4. Which module writes rows from dictionaries to CSV?
csv.DictWriter takes dictionaries and a list of field names and handles quoting for you.Q5. Why wrap each item in try and except in a batch job?
Q6. Who normally starts a scheduled Python script?
Frequently asked questions
What should I automate first?
+Pick a task you already do every week, such as tidying a folder or building a report. Small and familiar tasks teach you the tools without the pressure of a big project.
Is it safe to test on my real files?
+Test on a copy or on a temporary folder first, and use a dry run. Once the plan looks right, run it on the real folder.
Do I need extra libraries for automation?
+Not to start. pathlib, shutil, csv, logging and datetime are all in the standard library and cover most file jobs.
How do I run a script every day?
+Use cron on Linux or macOS, Task Scheduler on Windows, or a scheduled workflow on a hosted service. See the scheduling lesson above for the cron fields.
Why use a temporary folder in examples?
+It lets the code create and delete files freely without touching your real data, and it cleans up after itself.
Key takeaways
- βEstimate the payback of a task before you automate it.
- βUse
pathlib.Pathfor every path and join parts with/. - βSeparate deciding from doing, so the plan can be tested and previewed.
- βAlways build a dry run for anything that renames, moves or deletes.
- βLog what an unattended script does and continue past single failures.
- βAim for idempotent scripts that are safe to run twice.