
Python for automation, part 2: files, CSV, Excel, and report by mail
🌐 Machine-translated from Russian. Show original
In this part:
pathlib — pain-free paths#
The pathlib module works the same on Windows and Linux, and paths can be written through direct slash even on Windows.
from datetime import datetime, timedelta
from pathlib import Path
base = Path("D:/exchange") # на Linux, например, Path("/srv/exchange")
report = base / "out" / f"report_{datetime.now():%Y-%m-%d}.xlsx"
report.parent.mkdir(parents=True, exist_ok=True)
print(report.name, report.suffix, report.stem)
print(report.exists())
# все CSV в папке и подпапках
for f in base.rglob("*.csv"):
print(f, f.stat().st_size)
Windows network folders also work: Path("//fileserver/exchange") — Python understands UNC paths with direct slashes.
Example: cleaning old files with a "trial run"#
Any script it removes should first run in "show only" mode.
import argparse
import time
from pathlib import Path
def cleanup(folder: Path, days: int, pattern: str, dry_run: bool) -> int:
border = time.time() - days * 86400
removed = 0
for f in folder.rglob(pattern):
if f.is_file() and f.stat().st_mtime < border:
print(("[dry-run] " if dry_run else "") + f"удаляю {f}")
if not dry_run:
f.unlink()
removed += 1
return removed
if __name__ == "__main__":
p = argparse.ArgumentParser(description="Удаление файлов старше N дней")
p.add_argument("folder", type=Path)
p.add_argument("--days", type=int, default=30)
p.add_argument("--pattern", default="*.log")
p.add_argument("--apply", action="store_true", help="действительно удалить")
a = p.parse_args()
n = cleanup(a.folder, a.days, a.pattern, dry_run=not a.apply)
print(f"Файлов: {n}")
python cleanup.py /var/log/myapp --days 14 # только список
python cleanup.py /var/log/myapp --days 14 --apply # удаление
CSV: encodings and delimiters#
The main problem is files from Excel and 1C. Russian Excel saves "CSV (semicolons)" with semicolons and often in cp1251 encoding, and "CSV UTF-8" with BOM.
import csv
from pathlib import Path
def read_csv(path: Path) -> list[dict]:
for enc in ("utf-8-sig", "cp1251"): # utf-8-sig понимает и обычный UTF-8, и UTF-8 с BOM
try:
text = path.read_text(encoding=enc)
break
except UnicodeDecodeError:
continue
else:
raise ValueError(f"Не удалось определить кодировку {path}")
dialect = csv.Sniffer().sniff(text[:4096], delimiters=";,")
return list(csv.DictReader(text.splitlines(), dialect=dialect))
rows = read_csv(Path("sales.csv"))
print(rows[0]) # {'Дата': '01.11.2026', 'Филиал': 'Астана', 'Сумма': '125000,50'}
Numbers with commas (125000,50) are converted as: float(s.replace(" ", "").replace(",", ".")).
CSV record that Excel will open without "crabby":
with open("out.csv", "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f, delimiter=";")
w.writerow(["Сервер", "Статус"])
w.writerow(["srv-1c", "OK"])
Excel via openpyxl: a beautiful report#
openpyxl reads and writes .xlsx without Excel installed — suitable for a server. The old format .xls not supported.
uv add openpyxl
from datetime import date
from pathlib import Path
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter
def make_report(rows: list[dict], path: Path) -> Path:
wb = Workbook()
ws = wb.active
ws.title = "Продажи"
headers = ["Дата", "Филиал", "Сумма, ₸"]
ws.append(headers)
for r in rows:
ws.append([r["date"], r["branch"], r["amount"]])
# шапка
head_fill = PatternFill("solid", fgColor="1F4E78")
for cell in ws[1]:
cell.font = Font(bold=True, color="FFFFFF")
cell.fill = head_fill
cell.alignment = Alignment(horizontal="center")
# форматы
for row in ws.iter_rows(min_row=2):
row[0].number_format = "DD.MM.YYYY"
row[2].number_format = "#,##0.00" # в русском Excel покажется как 125 000,50
# итог формулой — Excel пересчитает при открытии
last = ws.max_row
ws.append(["", "Итого", f"=SUM(C2:C{last})"])
ws.cell(row=last + 1, column=2).font = Font(bold=True)
ws.cell(row=last + 1, column=3).font = Font(bold=True)
ws.cell(row=last + 1, column=3).number_format = "#,##0.00"
# ширина колонок, закрепление шапки, автофильтр
for i, h in enumerate(headers, start=1):
width = max(len(str(c.value or "")) for c in ws[get_column_letter(i)]) + 2
ws.column_dimensions[get_column_letter(i)].width = min(max(width, len(h) + 2), 50)
ws.freeze_panes = "A2"
ws.auto_filter.ref = f"A1:C{last}"
path.parent.mkdir(parents=True, exist_ok=True)
wb.save(path)
return path
rows = [
{"date": date(2026, 11, 9), "branch": "Астана", "amount": 125000.5},
{"date": date(2026, 11, 9), "branch": "Алматы", "amount": 98000},
]
print(make_report(rows, Path("out/sales.xlsx")))
Reading an existing book:
from openpyxl import load_workbook
wb = load_workbook("price.xlsx", read_only=True, data_only=True) # data_only — значения, а не формулы
ws = wb["Лист1"]
for code, name, price in ws.iter_rows(min_row=2, max_col=3, values_only=True):
print(code, name, price)
wb.close()
⚠️
data_only=Truereturns the values of formulas saved by Excel when last saved. If the file was created by openpyxl and was not opened in Excel, the formulas have no values — it will beNone.
PANDAS: When to Count#
For groupings, pivot tables, and merging multiple sources, pandas is more convenient. For writing in Excel, it also needs openpyxl.
uv add pandas openpyxl
import pandas as pd
df = pd.read_csv("sales.csv", sep=";", encoding="utf-8-sig", decimal=",", parse_dates=["Дата"], dayfirst=True)
by_branch = (
df.groupby("Филиал", as_index=False)["Сумма"]
.sum()
.sort_values("Сумма", ascending=False)
)
pivot = df.pivot_table(index="Филиал", columns=df["Дата"].dt.strftime("%Y-%m"), values="Сумма", aggfunc="sum", fill_value=0)
with pd.ExcelWriter("out/summary.xlsx", engine="openpyxl") as xw:
by_branch.to_excel(xw, sheet_name="По филиалам", index=False)
pivot.to_excel(xw, sheet_name="По месяцам")
df.to_excel(xw, sheet_name="Исходные данные", index=False)
In pandas 3.x, Copy-on-Write and a separate string data type are enabled by default. If you transfer old scripts from pandas 1.x/2.x, run them onto test data: chains of the df[df.a > 0]["b"] = 1 no longer modify the original table — write df.loc[df.a > 0, "b"] = 1.
openpyxl or pandas? You need formatting, formulas, specific template cells — openpyxl. You need to count and export tables — pandas. Often together: pandas counts, openpyxl completes the formatting.
Sending the report by mail#
Standard library: smtplib + email.message.EmailMessage.
import mimetypes
import smtplib
from email.message import EmailMessage
from pathlib import Path
from pyreports.config import need, opt
def send_report(to: list[str], subject: str, text: str, attachments: list[Path]) -> None:
msg = EmailMessage()
msg["From"] = need("SMTP_USER")
msg["To"] = ", ".join(to)
msg["Subject"] = subject
msg.set_content(text)
for path in attachments:
ctype, _ = mimetypes.guess_type(path.name)
maintype, subtype = (ctype or "application/octet-stream").split("/", 1)
msg.add_attachment(path.read_bytes(), maintype=maintype, subtype=subtype, filename=path.name)
host = need("SMTP_HOST")
port = int(opt("SMTP_PORT", "587"))
with smtplib.SMTP(host, port, timeout=30) as smtp:
smtp.starttls() # шифруем соединение
smtp.login(need("SMTP_USER"), need("SMTP_PASSWORD"))
smtp.send_message(msg)
send_report(
to=["director@company.kz", "finance@company.kz"],
subject="Продажи за 09.11.2026",
text="Добрый день! Во вложении отчет о продажах за вчера.",
attachments=[Path("out/sales.xlsx")],
)
Practice:
- Set up a separate mailbox for mailings instead of using a personal one.
- Port 465 is
smtplib.SMTP_SSL, port 587 isSMTP+starttls(). Sending without encryption and authorization is only allowed if the internal relay is configured this way and it is approved by security. - Microsoft 365 and Google Workspace for new integrations restrict password login (Basic Auth) and require OAuth 2.0 or separate mechanisms (e.g., Microsoft Graph API). Check with your mail administrator which method is allowed.
- If the report contains personal data, encrypt the archive or upload the file to a shared folder with permissions, and send the link by email.
Assembly: daily full report#
# src/pyreports/daily.py
import logging
import sys
from datetime import date, timedelta
from pathlib import Path
log = logging.getLogger("pyreports.daily")
def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
day = date.today() - timedelta(days=1)
try:
rows = load_sales(day) # из CSV, базы или API — см. следующую часть
path = make_report(rows, Path(f"out/sales_{day:%Y-%m-%d}.xlsx"))
send_report(["director@company.kz"], f"Продажи за {day:%d.%m.%Y}", "Отчет во вложении.", [path])
except Exception:
log.exception("Отчет не сформирован")
return 1
log.info("Отчет за %s отправлен", day)
return 0
if __name__ == "__main__":
sys.exit(main())
The next part is API and web: Python for automation, part 3: API, JSON, query repetitions, and secrets.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.