By the end you'll know
- How to read and write Excel files from Python, with
openpyxl - The ways real spreadsheets go wrong, and how to catch each one
- Why a report that says "incomplete" is better than one that's quietly wrong
- How to email a report with an attachment, and test it without sending anything real
- How to write a test for each problem, so it stays caught
Before you start
- You need: Docker, as in the Linux track's first lessons, and the practice folder:
git clone https://github.com/Kwamib/automation-practice.git, orgit pullin it. - This lesson uses Python from the Python track: functions, lists and dictionaries, reading files, virtual environments, exit codes and tests. If those are new, start there.
- Where commands run: in a Python container on your own computer, with a second container catching the email.
- The output below is from a real run on November 19, 2026, just after midnight in New York (05:08 UTC).
The problem: Monday morning copy and paste
The bookshop has five branches: North, South, East, West and Central. Every Monday, each branch manager saves last week's sales as an Excel file in a shared folder, and someone at head office opens all five, copies the totals into a summary, and emails it round. It takes an hour, it's dull, and nobody checks it.
This is the most common kind of automation there is. It's not on a server, and it's not about infrastructure: it's the work on people's desks. Job listings for analysts, operations and support roles ask for it all the time, as "automating reports" or "Python scripting for Excel". It also has a famous book: Al Sweigart's Automate the Boring Stuff with Python, free to read online, which is full of jobs like this one.
It looks like a ten-line script. It isn't, because people make spreadsheets, and people do things a script doesn't expect.
The lab
On your own computer, two containers: one for Python, and Mailpit, a fake mail server. It accepts email like a real one, sends nothing anywhere, and shows what it received on a web page.
cd ~/Apps/automation-practice/report
docker network create report-lab
docker run -d --name mailpit --network report-lab -p 8025:8025 axllent/mailpit
docker run -it --rm --network report-lab -v "$PWD":/practice -w /practice python:3.12-slim bash
docker network create report-lab: a private network, so the two containers can reach each other by name.docker run -d --name mailpit ...: starts Mailpit in the background (-d), namedmailpit.-p 8025:8025puts its web page at http://localhost:8025 on your computer.- The second
docker run: a Python container on the same network, with thereportfolder inside it at/practice.
(Inside the Python container)
python -m venv /tmp/venv && . /tmp/venv/bin/activate
pip install -q -r requirements.txt
python make_sales.py
5911 sales/2026-W46/branch-east.xlsx
5928 sales/2026-W46/branch-north.xlsx
5962 sales/2026-W46/branch-south.xlsx
5932 sales/2026-W46/branch-west.xlsx
44 sales/2026-W46/~$branch-north.xlsx
python -m venv /tmp/venv: a virtual environment, a private place for this project's packages.. /tmp/venv/bin/activateswitches to it (the.means "run this in the current shell").pip install -q -r requirements.txt: installs the packages the file lists, quietly (-q):openpyxl, which reads and writes Excel files, andpytest, for tests. Each at a fixed version, so the lab works the same next year.python make_sales.py: makes this week's folder of made-up spreadsheets.
The week is 2026-W46: week 46 of 2026, Monday 9 to Sunday 15 November. That's the ISO week, a numbering most businesses use, where weeks start on Monday.
Each file has one sheet, Sales, with a row per sale: date, isbn, title, quantity, price and amount. And, like real files, each has a story:
| Branch | What happened |
|---|---|
| North | A good file, but still open in Excel on someone's computer. Excel leaves a small "owner file" next to it, ~$branch-north.xlsx, while it's open. |
| South | The manager added a blank row, and a TOTAL row at the bottom, as people do. |
| East | One quantity typed as text with a space, "3 ", and one typed as a word, "two". |
| West | Sent last week's file again, by mistake, under this week's name. |
| Central | Didn't send anything. |
The quick way
naive.py, the script anyone would write first:
"""naive.py: the quick way. Add up the "amount" column of every spreadsheet
in a folder. It prints a confident total. Is it right?
python naive.py sales/2026-W46
python naive.py sales/2026-W46 'branch-*.xlsx' (only files matching a pattern)
"""
import pathlib
import sys
from openpyxl import load_workbook
total = 0
for path in sorted(pathlib.Path(sys.argv[1]).glob(sys.argv[2] if len(sys.argv) > 2 else "*.xlsx")):
ws = load_workbook(path).active
for row in ws.iter_rows(min_row=2, values_only=True):
if row and isinstance(row[5], (int, float)):
total += row[5]
print(f"added {path.name}")
print(f"Total sales this week: ${total:,.2f}")
pathlib.Path(folder).glob("*.xlsx"): every file in the folder whose name ends.xlsx.load_workbook(path).active: open the file, and take the sheet that was showing when it was saved.ws.iter_rows(min_row=2, values_only=True): each row after the headings, as plain values.row[5]: the sixth column,amount. If it's a number, add it.
python naive.py sales/2026-W46
added branch-east.xlsx
added branch-north.xlsx
added branch-south.xlsx
added branch-west.xlsx
Traceback (most recent call last):
File "/practice/naive.py", line 14, in <module>
ws = load_workbook(path).active
...
zipfile.BadZipFile: File is not a zip file
It crashed on Excel's owner file. ~$branch-north.xlsx ends in .xlsx, but it isn't a spreadsheet: an .xlsx file is really a zip file, and this is 44 bytes of something else. So the quick fix is to only read files starting branch-:
python naive.py sales/2026-W46 'branch-*.xlsx'
added branch-east.xlsx
added branch-north.xlsx
added branch-south.xlsx
added branch-west.xlsx
Total sales this week: $4,466.61
A clean, confident number. It's wrong in four ways, and nothing on the screen says so:
- South's TOTAL row was added as if it were more sales, so South counted twice.
- West's sales are last week's.
- East's "two" row was counted, from its
amountcolumn, even though nobody knows what the quantity really was. - Central is missing, and the total doesn't say so. Four branches' sales look like the whole business.
This is the dangerous kind of automation: it does the job faster than a person, and makes mistakes a person would have spotted.
The real report
weekly_report.py, also on GitHub (opens in a new tab):
"""weekly_report.py: build the bookshop's weekly sales report from the branches'
spreadsheets, and email it.
python weekly_report.py --week 2026-W46 build the report, send nothing
python weekly_report.py --week 2026-W46 --send build it, and email it
Settings come from the environment, so the same script runs anywhere:
SALES_DIR where the branches' folders are (default: sales)
REPORT_DIR where reports are written (default: reports)
SMTP_HOST, SMTP_PORT, REPORT_FROM, REPORT_TO where the email goes
SMTP_USER, SMTP_PASSWORD only if the mail server needs a login
Exit codes: 0 every branch's file was good; 1 the report was built but is
incomplete (a branch's file is missing or was rejected, and the report says
which); 2 called wrongly, or a setup problem.
"""
import argparse
import datetime
import logging
import os
import pathlib
import smtplib
import sys
import tempfile
import time
from collections import defaultdict
from dataclasses import dataclass, field
from email.message import EmailMessage
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font
BRANCHES = ["north", "south", "east", "west", "central"]
HEADERS = ["date", "isbn", "title", "quantity", "price", "amount"]
TOTAL_WORDS = {"total", "totals", "grand total", "sum"}
logging.Formatter.converter = time.gmtime
logging.basicConfig(format="%(asctime)sZ weekly_report: %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S", level=logging.INFO)
log = logging.getLogger()
class BadFile(Exception):
"""A branch's file can't be used. The message says why, for a person to fix."""
@dataclass
class Branch:
name: str
status: str = "missing" # ok, missing or rejected
reason: str = ""
rows: list = field(default_factory=list)
notes: list = field(default_factory=list)
@property
def units(self):
return sum(r[2] for r in self.rows)
@property
def sales(self):
return round(sum(r[2] * r[3] for r in self.rows), 2)
def week_dates(week):
"""'2026-W46' -> (Monday, Sunday) of that ISO week."""
try:
year, num = week.split("-W")
monday = datetime.date.fromisocalendar(int(year), int(num), 1)
except ValueError:
raise SystemExit(f"--week must look like 2026-W46, not {week!r}") from None
return monday, monday + datetime.timedelta(days=6)
def whole_number(value, where, notes):
if isinstance(value, bool):
raise BadFile(f"{where}: quantity {value!r} isn't a whole number")
if isinstance(value, int):
return value
if isinstance(value, float) and value.is_integer():
return int(value)
if isinstance(value, str) and value.strip().isdigit():
notes.append(f"{where}: quantity {value!r} was typed as text; read it as {int(value.strip())}")
return int(value.strip())
raise BadFile(f"{where}: quantity {value!r} isn't a whole number")
def read_branch(path, monday, sunday):
"""Read one branch's file. Returns (rows, notes), or raises BadFile.
All of a file, or none of it: one bad row rejects the whole file."""
notes, rows = [], []
try:
wb = load_workbook(path, read_only=True, data_only=True)
except Exception as e:
raise BadFile(f"it isn't a spreadsheet Excel can open ({e})") from None
if "Sales" not in wb.sheetnames:
raise BadFile(f"there's no sheet called Sales (it has: {', '.join(wb.sheetnames)})")
sheet = wb["Sales"].iter_rows(values_only=True)
header = [str(c).strip().lower() if c is not None else "" for c in next(sheet, ())]
if header[:len(HEADERS)] != HEADERS:
raise BadFile(f"the columns are {header}, not {HEADERS}")
for n, row in enumerate(sheet, start=2):
where = f"row {n}"
cells = (list(row) + [None] * len(HEADERS))[:len(HEADERS)]
if all(c is None or str(c).strip() == "" for c in cells):
continue
day, isbn, title, qty, price, amount = cells
if day is None and isbn is None and str(title).strip().lower() in TOTAL_WORDS:
notes.append(f"{where}: skipped a totals row, so it isn't counted twice")
continue
if not isinstance(day, datetime.datetime):
raise BadFile(f"{where}: date {day!r} isn't a date")
if not monday <= day.date() <= sunday:
raise BadFile(f"{where}: date {day.date()} isn't in this week ({monday} to {sunday}); is this last week's file?")
isbn = str(isbn).strip()
if not (isbn.isdigit() and len(isbn) == 13):
raise BadFile(f"{where}: ISBN {isbn!r} isn't 13 digits")
qty = whole_number(qty, where, notes)
if not isinstance(price, (int, float)) or price <= 0:
raise BadFile(f"{where}: price {price!r} isn't a positive number")
if isinstance(amount, (int, float)) and abs(amount - qty * price) > 0.005:
raise BadFile(f"{where}: amount {amount} isn't quantity x price ({qty} x {price})")
rows.append((isbn, str(title).strip(), qty, float(price)))
if not rows:
raise BadFile("it has no sales rows")
return rows, notes
def gather(folder, monday, sunday):
branches = []
for name in BRANCHES:
b = Branch(name)
path = folder / f"branch-{name}.xlsx"
if (folder / f"~$branch-{name}.xlsx").exists():
b.notes.append("the file is open in Excel on someone's computer, so it may have unsaved changes")
if not path.exists():
b.reason = f"no file called {path.name}"
log.info(f"{name}: MISSING ({b.reason})")
else:
try:
b.rows, notes = read_branch(path, monday, sunday)
b.notes += notes
b.status = "ok"
log.info(f"{name}: ok, {len(b.rows)} lines, {b.units} books, ${b.sales:,.2f}")
except BadFile as e:
b.status, b.reason = "rejected", str(e)
log.info(f"{name}: REJECTED ({b.reason})")
for note in b.notes:
log.info(f"{name}: note: {note}")
branches.append(b)
expected = {f"branch-{n}.xlsx" for n in BRANCHES} | {f"~$branch-{n}.xlsx" for n in BRANCHES}
for p in sorted(folder.iterdir()):
if p.name not in expected:
log.info(f"ignored a file nobody expects: {p.name}")
return branches
def build_workbook(week, monday, sunday, branches):
good = [b for b in branches if b.status == "ok"]
problems = [b for b in branches if b.status != "ok"]
wb = Workbook()
ws = wb.active
ws.title = "Summary"
bold = Font(bold=True)
ws.append([f"Bookshop weekly sales, {week} ({monday:%d %B} to {sunday:%d %B %Y})"])
ws["A1"].font = Font(bold=True, size=14)
if problems:
ws.append([f"INCOMPLETE: {len(good)} of {len(branches)} branches. Not included: "
+ "; ".join(f"{b.name} ({b.status}: {b.reason})" for b in problems)])
ws["A2"].font = Font(bold=True, color="C00000")
else:
ws.append(["Complete: every branch's file was checked and included."])
ws.append([])
ws.append(["Branch", "Status", "Lines", "Books sold", "Sales", "Notes"])
for c in ws[ws.max_row]:
c.font = bold
for b in branches:
ws.append([b.name, b.status, len(b.rows) or None, b.units or None, b.sales or None,
"; ".join(([b.reason] if b.reason else []) + b.notes)])
ws.append(["Total", f"{len(good)} of {len(branches)} branches", sum(len(b.rows) for b in good),
sum(b.units for b in good), round(sum(b.sales for b in good), 2), ""])
for c in ws[ws.max_row]:
c.font = bold
for row in ws.iter_rows(min_row=5, min_col=5, max_col=5):
row[0].number_format = "$#,##0.00"
for col, width in zip("ABCDEF", (12, 26, 8, 12, 14, 90)):
ws.column_dimensions[col].width = width
top = wb.create_sheet("Top books")
top.append(["Title", "Books sold", "Sales"])
for c in top[1]:
c.font = bold
by_title = defaultdict(lambda: [0, 0.0])
for b in good:
for _, title, qty, price in b.rows:
by_title[title][0] += qty
by_title[title][1] += qty * price
for title, (units, sales) in sorted(by_title.items(), key=lambda kv: -kv[1][1]):
top.append([title, units, round(sales, 2)])
top.cell(top.max_row, 3).number_format = "$#,##0.00"
for col, width in zip("ABC", (30, 12, 14)):
top.column_dimensions[col].width = width
return wb
def save_atomically(wb, path):
"""Write to a temporary file in the same folder, then rename: nobody ever
opens half a report."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".report-", suffix=".xlsx")
os.close(fd)
try:
wb.save(tmp)
os.chmod(tmp, 0o644)
os.replace(tmp, path)
except BaseException:
os.unlink(tmp)
raise
def summary_text(week, branches):
good = [b for b in branches if b.status == "ok"]
lines = [f"Weekly sales, {week}", ""]
for b in branches:
if b.status == "ok":
lines.append(f" {b.name:<8} ${b.sales:>10,.2f} ({b.units} books)")
else:
lines.append(f" {b.name:<8} {b.status.upper()}: {b.reason}")
lines += ["", f" Total ${sum(b.sales for b in good):>10,.2f} from {len(good)} of {len(branches)} branches"]
if len(good) < len(branches):
lines += ["", "This report is INCOMPLETE. The branches above need to send a corrected file."]
lines += ["", "The full report is attached. Sent by weekly_report.py."]
return "\n".join(lines)
def send(path, subject, body):
env = os.environ
missing = [k for k in ("SMTP_HOST", "REPORT_FROM", "REPORT_TO") if not env.get(k)]
if missing:
raise SystemExit(f"can't send: set {', '.join(missing)}")
msg = EmailMessage()
msg["Subject"], msg["From"], msg["To"] = subject, env["REPORT_FROM"], env["REPORT_TO"]
msg.set_content(body)
msg.add_attachment(path.read_bytes(), maintype="application",
subtype="vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename=path.name)
with smtplib.SMTP(env["SMTP_HOST"], int(env.get("SMTP_PORT", "25")), timeout=15) as smtp:
if env.get("SMTP_USER"): # a real mail server: encrypt, then log in
smtp.starttls()
smtp.login(env["SMTP_USER"], env["SMTP_PASSWORD"])
smtp.send_message(msg)
log.info(f"emailed the report to {env['REPORT_TO']}")
def main(argv=None):
p = argparse.ArgumentParser(description="Build the weekly sales report, and email it with --send.")
p.add_argument("--week", required=True, help="the ISO week, like 2026-W46")
p.add_argument("--send", action="store_true", help="email the report (without it, nothing is sent)")
args = p.parse_args(argv)
monday, sunday = week_dates(args.week)
folder = pathlib.Path(os.environ.get("SALES_DIR", "sales")) / args.week
if not folder.is_dir():
log.info(f"no folder {folder}: nothing to report on")
return 2
branches = gather(folder, monday, sunday)
good = [b for b in branches if b.status == "ok"]
path = pathlib.Path(os.environ.get("REPORT_DIR", "reports")) / f"sales-{args.week}.xlsx"
save_atomically(build_workbook(args.week, monday, sunday, branches), path)
total = sum(b.sales for b in good)
complete = len(good) == len(branches)
subject = (f"Weekly sales {args.week}: ${total:,.2f} from {len(good)} of {len(branches)} branches"
+ ("" if complete else " (INCOMPLETE)"))
log.info(f"wrote {path}: {subject}")
print(summary_text(args.week, branches))
if args.send:
send(path, subject, summary_text(args.week, branches))
else:
log.info("not sending: add --send to email it")
return 0 if complete else 1
if __name__ == "__main__":
sys.exit(main())
It's longer, because it does the checking the person used to do in their head. Taking it in order.
Settings from outside the code
The folders and the mail server come from environment variables (os.environ), with sensible defaults, as in the Python track's Alerts and settings. The same script runs in this lab, on a server and on a colleague's laptop without editing it, and passwords never go in the code.
argparse handles the command line: --week is required, and --send is off unless you ask. As in every lesson in this track, the risky part, emailing a whole list of people, is something you ask for, not the default.
Expect five branches, by name
BRANCHES lists who should send a file. The script looks for each one by name (branch-north.xlsx and so on), rather than reading "whatever's in the folder". That's what makes a missing branch visible: the quick script couldn't tell four files from five. And a file nobody expects, like branch-north-old.xlsx, is logged and ignored, not added in.
Check every file before trusting it
read_branch reads one file, and raises BadFile with a reason a person can act on at the first problem. One bad row rejects the whole file, as with Lesson 3's supplier files: all of a file, or none of it.
| Check | Catches |
|---|---|
| Can it be opened as a spreadsheet? | Excel's ~$ owner files, a file saved in the wrong format |
Is there a sheet called Sales, with the expected columns? | A renamed sheet, columns moved or renamed |
| Is the date a date, inside this week? | West's file from last week |
| Is the ISBN 13 digits? | A typo in a book's number |
| Is the quantity a whole number? | East's "two"; and "3 ", which it accepts as 3, with a note |
| Is the price a positive number? | "free", a blank, a negative price |
Is amount quantity times price? | A row someone edited by hand |
Two kinds of row are skipped on purpose, and noted: blank rows, and totals rows (no date, no ISBN, and a title like "TOTAL"). The script works out totals itself, from quantity times price, and never trusts a total someone typed.
Some things aren't wrong, just worth knowing. Those become notes, not rejections: a number typed as text, a skipped totals row, and a file that's open in Excel (~$branch-north.xlsx exists), which may mean someone's still working on it.
Say what's missing, loudly
A report with three branches missing is still useful, as long as it says so. The report is built either way. When anything's missing or rejected, the summary sheet's second line, the email's subject line and the email's text all say INCOMPLETE, and name each branch and why. And the script exits 1, so anything scheduling it knows.
A report people can read
build_workbook makes a new Excel file with two sheets:
- Summary: a title with the week's dates, the complete or INCOMPLETE line in red, a row per branch with its status, lines, books sold, sales and notes, and a total of the good branches. Headings in bold, money as
$#,##0.00, and columns wide enough to read. - Top books: every title, by sales, across the good branches.
openpyxl does all of this: Workbook() makes a new file, ws.append([...]) adds a row, Font(bold=True) makes text bold, cell.number_format sets how a number is shown, and ws.column_dimensions["A"].width sets a column's width.
Never half a report
save_atomically writes the report to a temporary file in the same folder (tempfile.mkstemp), then renames it into place with os.replace, the same trick as Lesson 1's Bash script. Anyone opening sales-2026-W46.xlsx gets last week's finished report or this week's, never half of one.
Email it
send builds the email with Python's EmailMessage: a subject, who it's from and to, the summary as plain text, and the report attached with add_attachment, labeled with the Excel file type. smtplib.SMTP(host, port) connects to the mail server and sends it. For a real mail server, which needs a login, it encrypts the connection first (starttls()), then logs in with a username and password from the environment. Mailpit needs neither.
Run it
python weekly_report.py --week 2026-W46; echo "exit $?"
2026-11-19T05:07:59Z weekly_report: north: ok, 30 lines, 86 books, $869.14
2026-11-19T05:07:59Z weekly_report: north: note: the file is open in Excel on someone's computer, so it may have unsaved changes
2026-11-19T05:07:59Z weekly_report: south: ok, 30 lines, 91 books, $920.09
2026-11-19T05:07:59Z weekly_report: south: note: row 33: skipped a totals row, so it isn't counted twice
2026-11-19T05:07:59Z weekly_report: east: REJECTED (row 11: quantity 'two' isn't a whole number)
2026-11-19T05:07:59Z weekly_report: west: REJECTED (row 2: date 2026-11-02 isn't in this week (2026-11-09 to 2026-11-15); is this last week's file?)
2026-11-19T05:07:59Z weekly_report: central: MISSING (no file called branch-central.xlsx)
2026-11-19T05:07:59Z weekly_report: wrote reports/sales-2026-W46.xlsx: Weekly sales 2026-W46: $1,789.23 from 2 of 5 branches (INCOMPLETE)
Weekly sales, 2026-W46
north $ 869.14 (86 books)
south $ 920.09 (91 books)
east REJECTED: row 11: quantity 'two' isn't a whole number
west REJECTED: row 2: date 2026-11-02 isn't in this week (2026-11-09 to 2026-11-15); is this last week's file?
central MISSING: no file called branch-central.xlsx
Total $ 1,789.23 from 2 of 5 branches
This report is INCOMPLETE. The branches above need to send a corrected file.
The full report is attached. Sent by weekly_report.py.
2026-11-19T05:07:59Z weekly_report: not sending: add --send to email it
exit 1
Every one of the five stories is named: North open in Excel, South's totals row skipped, East's "two" and the row it's on, West's file from last week, and Central missing. The total is $1,789.23 from 2 of 5 branches, smaller and true, where the quick script said $4,466.61 with no warnings. Exit 1: built, but incomplete.
Send it
export SMTP_HOST=mailpit SMTP_PORT=1025 REPORT_FROM=reports@bookshop.example REPORT_TO=managers@bookshop.example
python weekly_report.py --week 2026-W46 --send; echo "exit $?"
...
2026-11-19T05:08:08Z weekly_report: emailed the report to managers@bookshop.example
exit 1
export NAME=value ...: sets those settings for every command after it.mailpitis the other container's name; 1025 is its mail port. Addresses ending.examplecan never be real ones.
In Mailpit, at http://localhost:8025, the email arrives with the report attached. Here's the inbox at the end of the lab, with this email at the bottom, and the one from the next section above it:
The subject line alone tells a manager the numbers aren't complete, before they open anything.
The branches resend
East fixes "two", West sends this week's file, Central sends theirs, and North's file is closed:
python make_sales.py --resend
python weekly_report.py --week 2026-W46 --send; echo "exit $?"
2026-11-19T05:08:27Z weekly_report: north: ok, 30 lines, 86 books, $869.14
2026-11-19T05:08:27Z weekly_report: south: ok, 30 lines, 91 books, $920.09
2026-11-19T05:08:27Z weekly_report: south: note: row 33: skipped a totals row, so it isn't counted twice
2026-11-19T05:08:27Z weekly_report: east: ok, 28 lines, 80 books, $823.20
2026-11-19T05:08:27Z weekly_report: east: note: row 6: quantity '3 ' was typed as text; read it as 3
2026-11-19T05:08:27Z weekly_report: west: ok, 30 lines, 89 books, $914.11
2026-11-19T05:08:27Z weekly_report: central: ok, 30 lines, 94 books, $965.06
2026-11-19T05:08:27Z weekly_report: wrote reports/sales-2026-W46.xlsx: Weekly sales 2026-W46: $4,491.60 from 5 of 5 branches
...
Total $ 4,491.60 from 5 of 5 branches
...
2026-11-19T05:08:27Z weekly_report: emailed the report to managers@bookshop.example
exit 0
Five of five, $4,491.60, exit 0, and a second email, "from 5 of 5 branches", with no INCOMPLETE. East's "3 " is now noted, since the rest of its file is good.
And the quick script, on the same corrected files:
python naive.py sales/2026-W46 'branch-*.xlsx'
Total sales this week: $5,411.69
$920.09 too much, which is exactly South's sales. Even with every file corrected, South's TOTAL row is counted as more sales, every single week. Nobody would notice: it's a plausible number.
Tests for every problem
Each problem the report catches has a test in test_weekly_report.py. Each test makes a tiny spreadsheet with exactly one problem in it, and checks the script deals with it:
def test_a_totals_row_is_skipped_not_counted(tmp_path):
rows, notes = wr.read_branch(sheet(tmp_path, GOOD, [], [None, None, "TOTAL", 2, None, 17.98]), MONDAY, SUNDAY)
assert len(rows) == 1
assert "totals row" in notes[0]
tmp_path: a fresh, empty folderpytestgives each test, deleted afterwards.sheet(...): a helper in the test file that saves a small spreadsheet with the rows given.assert: the test fails if this isn't true. Here: one real row was read, and the totals row was noted, not counted.@pytest.mark.parametrizeruns one test several times with different data. Here, it runs five different bad rows, and checks each rejects the file with the right reason.
python -m pytest -v
test_weekly_report.py::test_a_good_file_is_read PASSED [ 8%]
test_weekly_report.py::test_a_totals_row_is_skipped_not_counted PASSED [ 16%]
test_weekly_report.py::test_a_number_typed_as_text_is_read_and_noted PASSED [ 25%]
test_weekly_report.py::test_one_bad_row_rejects_the_whole_file[row0-isn't a whole number] PASSED [ 33%]
test_weekly_report.py::test_one_bad_row_rejects_the_whole_file[row1-isn't in this week] PASSED [ 41%]
test_weekly_report.py::test_one_bad_row_rejects_the_whole_file[row2-isn't 13 digits] PASSED [ 50%]
test_weekly_report.py::test_one_bad_row_rejects_the_whole_file[row3-isn't quantity x price] PASSED [ 58%]
test_weekly_report.py::test_one_bad_row_rejects_the_whole_file[row4-isn't a positive number] PASSED [ 66%]
test_weekly_report.py::test_wrong_columns_are_rejected PASSED [ 75%]
test_weekly_report.py::test_a_file_that_isnt_a_spreadsheet_is_rejected PASSED [ 83%]
test_weekly_report.py::test_missing_branches_and_excel_lock_files PASSED [ 91%]
test_weekly_report.py::test_an_incomplete_week_says_so_and_exits_1 PASSED [100%]
12 passed in 0.13s
Twelve problems, each caught, in a seventh of a second. Next month, when a branch finds a new way to break a spreadsheet, you add a check and a test for it, and the old twelve keep you from breaking what already works. Tests are how a report stays trustworthy as it grows.
Run it every Monday
The report is ready to schedule, with any of this track's tools. On a server, a systemd timer like Lesson 2's:
[Timer]
OnCalendar=Mon *-*-* 07:05:00
Persistent=true
The service runs it for last week, with the virtual environment's Python and the mail settings in an environment file only root can read. And give it a heartbeat (Lesson 2's hc-ping): exit 1, "incomplete", should reach a person, and so should a Monday when it didn't run at all. Working out "last week" is a small trap of its own. Spot the problem below is about it.
Clean up
exit
(On your own computer)
docker rm -f mailpit
docker network rm report-lab
docker rm -f mailpit: stops and deletes the Mailpit container (-fmeans "even though it's running").docker network rm report-lab: deletes the network.
In real life
- Agree the template. Most of these problems disappear when every branch uses the same spreadsheet, with the sheet name, the columns and the data types fixed, and no space for a TOTAL row. Send each branch the template; keep the checks anyway.
- Real mail servers need a login and encryption. Use the company's mail server or an email service, with the username and password in the environment (or a secret store), never in the code.
starttls()thenlogin(), as the script does. - Think about who gets what. A report with sales figures, or anything personal, goes to the people who need it, not a whole department.
- Files often live in SharePoint, OneDrive or Google Drive, not a shared folder. Each has an API to download them, with its own login, which makes this script's first step a download.
- For big data, use
pandas. It reads Excel and CSV into tables you can sum, group and join in a line or two. For a weekly report of a few thousand rows,openpyxland plain Python are easier to read, check and test. - Clean up old reports with something like Lesson 1's
prune-backups.
Spot the problem
Work out what's wrong before you read the explanation.
"Why is every Monday report so small?" A team schedules the report for 7am every Monday, with --week set to the current week: date +%G-W%V, which prints this week in ISO format. Every Monday, the report says around $40 from 5 of 5 branches, complete, and exit 0. Nobody understands why sales have collapsed. What's wrong? At 7am on Monday, "this week" has only just started, so the script reports on today: a few early sales, from files the branches haven't even sent yet. The fix: report on last week: date -d "7 days ago" +%G-W%V. %G is the ISO year and %V the ISO week number, which keeps the first days of January in the right week. And test it: a function that works out last week's name from a date, with a test for a Monday in January, makes sure it's right in the week that's easiest to get wrong. (In a crontab line, % has a special meaning and must be written \%; in a systemd service, it's %%.)
Keep this
| To | Use |
|---|---|
| A virtual environment | python -m venv DIR, then . DIR/bin/activate |
| Install fixed versions of packages | pip install -r requirements.txt |
| Open an Excel file, values only | load_workbook(path, read_only=True, data_only=True) |
| Read a sheet row by row | wb["Sales"].iter_rows(values_only=True) |
| Make an Excel file | wb = Workbook(), ws.append([...]), wb.save(path) |
| Bold text, money format, column width | Font(bold=True), cell.number_format = "$#,##0.00", ws.column_dimensions["A"].width |
| Monday of an ISO week | datetime.date.fromisocalendar(year, week, 1) |
| Save a file all at once | tempfile.mkstemp(dir=...), write, os.replace(tmp, path) |
| An email with an attachment | EmailMessage(), set_content, add_attachment |
| Send it | smtplib.SMTP(host, port), starttls(), login(), send_message(msg) |
| One test, many cases | @pytest.mark.parametrize |
| Last week, in ISO format | date -d "7 days ago" +%G-W%V |
Where you are now
You've replaced an hour of Monday copy-and-paste with a script that checks every branch's spreadsheet before trusting it, names each problem in words a branch manager can act on, never adds up a TOTAL row or last week's sales, says INCOMPLETE when a branch is missing, writes a tidy Excel report all at once, and emails it with the state of the numbers in the subject line. You've watched the quick version produce a plausible total that's wrong every week, and written twelve tests that keep the real one right. Lesson 8, the last, is about jobs that are really workflows, passing work between several apps, and how to choose where each job in this track belongs.
Check yourself
The quick script crashed on ~$branch-north.xlsx. What is that file?
After the resends, the quick script said $5,411.69 and the report said $4,491.60. Why?
West sent last week's file under this week's name. How was it caught?
Central sent nothing. Why couldn't the quick script tell?
Why does the report exit 1 when it's incomplete, even though it was built and sent?
What does each test in test_weekly_report.py do?
Key terms
openpyxl: a Python package for reading and writing Excel (.xlsx) files.- ISO week: a week numbered the international way, starting on Monday, like
2026-W46. - Owner file: the small
~$file Excel leaves next to a spreadsheet while it's open. - Totals row: a row someone added with a total, which isn't a sale and must not be added in.
- Incomplete report: a report built without every expected file, that says so plainly.
- SMTP: the way email is sent from one computer to a mail server; Python's
smtplibspeaks it. - Mailpit: a fake mail server for testing, which catches email and shows it on a web page.
- Test: a small piece of code that checks one thing your code should do, run with
pytest.
Go deeper
- Automate the Boring Stuff with Python (opens in a new tab), Al Sweigart's book, free to read online: its chapters on Excel, PDFs and Word, CSV and JSON, and email are full of jobs like this one.
- The Python track: Files and data, Scripts you can trust for
main(), exit codes and tests, and Running it on a schedule. - openpyxl's documentation (opens in a new tab), for charts, formulas and styles.
- Python's email examples (opens in a new tab), for HTML emails and more attachments.
- Mailpit (opens in a new tab), for testing anything that sends email.
- Try: add a check that each branch's file has at least one sale on every day the branch is open, and a test for it. Then add a "Compared with last week" column to the Summary sheet, reading last week's report from
reports/.