Python / Automation

Stop rebuilding your CSV totals: a small Python script

Combine three sample rows into category totals with Python's standard library. See the result first, then run the script without changing your source file.

Aggregate a three-row CSV without changing the source file

A worked example with fictional data, not a customer result.

BEFORE / INPUT

books 1,200
software 600
books 800

AFTER / RESULT

books 2,000
software 600
Three sample records. The total stays 2,600.

The result to aim for

category,amount
books,2000
software,600

Console: 2600 total; 2 categories

The books rows add up to 2,000 and software adds up to 600, giving 2,600 in total. Three input rows become two categories. Use non-negative integers in one consistent unit. Unclosed quotes, extra or missing columns, negative amounts, decimals, and an input with no records stop the script before it creates a result.

Try it with this input

Start with this input

category,amount
books,1200
software,600
books,800

Follow these steps

  1. Check that Python 3 is available. On Windows, open PowerShell and run python --version or py --version. On macOS/Linux, open a terminal and run python3 --version. Use the command that reports Python 3.x; no package installation is needed.
  2. Create an empty working folder. Save the input as weekly.csv and the code as summarize.py, both as plain text in UTF-8. Check that the names do not end in .txt. Amounts must be non-negative integers in the same unit.
  3. In Windows PowerShell or a macOS/Linux terminal, run cd "full path to your working folder". Check the location with Get-Location in PowerShell or pwd on macOS/Linux. Then run dir in PowerShell or ls on macOS/Linux and confirm that both weekly.csv and summarize.py are listed.
  4. Run the script with the command you checked: python summarize.py or py summarize.py on Windows, or python3 summarize.py on macOS/Linux.
  5. Compare totals.csv and the console total with the expected result: 2,600 and two categories. If the script stops, use the troubleshooting notes below before using any result.
  6. For another run, copy weekly.csv and summarize.py into a new empty folder. An existing totals.csv makes the script stop rather than overwrite it.

Runnable example

import csv
from collections import defaultdict
from pathlib import Path

totals = defaultdict(int)
with Path("weekly.csv").open(encoding="utf-8-sig", newline="") as source:
    reader = csv.DictReader(source, strict=True)
    if len(reader.fieldnames or []) != 2 or set(reader.fieldnames) != {"category", "amount"}:
        raise ValueError("Expected category and amount columns")
    for line, row in enumerate(reader, start=2):
        if None in row or any(value is None for value in row.values()):
            raise ValueError(f"Wrong column count on line {line}")
        category = row["category"].strip()
        raw_amount = row["amount"].strip()
        if not category or category[0] in "=+-@" or not raw_amount.isascii() or not raw_amount.isdigit():
            raise ValueError(f"Invalid category or non-negative integer amount on line {line}")
        totals[category] += int(raw_amount)

if not totals:
    raise ValueError("No data rows; check the input export")

# Exclusive creation: an existing result is never overwritten.
with Path("totals.csv").open("x", encoding="utf-8", newline="") as target:
    writer = csv.writer(target)
    writer.writerow(["category", "amount"])
    writer.writerows(sorted(totals.items()))
print(f"{sum(totals.values())} total; {len(totals)} categories")

If the example stops

Python is not found, or Microsoft Store opens

The version check did not find Python 3. Follow the installation instructions for your OS on the Python website, then reopen the terminal. Use the command that reports Python 3.x. This example needs no packages from pip.

FileNotFoundError, or summarize.py cannot be opened

Check the working folder and file names. On Windows, open PowerShell and repeat the cd and Get-Location steps. If using Command Prompt instead, run cd /d "full path to your working folder": cd alone does not switch drives. On macOS/Linux, use cd and pwd. Then use dir or ls to find both files. If a name ends in .txt, check its contents and save it with the intended name.

FileExistsError: totals.csv

The script stopped to preserve an earlier result. Copy only weekly.csv and summarize.py into a new empty folder and run it there. Do not change the output mode from "x" to "w": that would overwrite the previous result.

UnicodeDecodeError, or garbled text in Excel

A UnicodeDecodeError can mean the input is not UTF-8. Save a copy in UTF-8 and try again. If the script succeeds but Excel displays garbled category names, use Data → From Text/CSV to import totals.csv and choose UTF-8.

csv.Error, or a column/amount ValueError

Check for unclosed quotes, extra columns, empty values, thousands separators, negative amounts, and decimals. For example, books,"1200"0 is malformed CSV. Compare against the original records and export a fresh copy from the source application. Do not delete a failing row or replace its amount with zero just to make the script finish.

ValueError: No data rows

The file has headers but no records. Do not treat missing input as a measured zero. Check the file, export filters, and reporting period. First confirm that the three-row example on this page works.

Check before using the result

  • Work on a copy and confirm that weekly.csv has not changed
  • Check both column names, encoding, and a consistent unit for every amount
  • Reconcile the input total of 2,600 with the output total of 2,600
  • Compare total setup, runtime, review, and repair time against the manual task

Would another approach fit better?

Scroll the table sideways to read all columns.

ApproachUse it whenCost or limitation
A spreadsheetThis is a small, one-off job that you can check by handLittle setup; repeated pasting and range selection can introduce mistakes
Python csv moduleThe category and amount columns stay consistent across repeated filesAdd input checks once; stop when the format changes instead of guessing
Screen automationThere is no usable export and only a screen-based step remainsA changed screen can break it. It is unnecessary for this CSV example

Next decision

Try three copies of the same format and record the results and effort. Stay with the standard library while it meets the need. Compare a paid tool only after identifying a specific missing transformation, its maintenance cost, and the total price.

No paid product is required for this example. This page does not link to a product offer.

More detail on the decision
Decision pointPractical answer
Reader problemRepetitive computer work keeps taking time from higher-value work
Decision ruleUse Python when the input is consistent, and stabilize a changing UI workflow before automating it
Trade-offFile-based work is easier to keep stable, while UI automation reaches more screens but breaks more easily
Concrete testNormalize a weekly CSV and produce one checked summary file
Failure to avoidAutomating several changing websites before proving one useful workflow
First actionWrite down one repeated task, its input, output, and current time cost
Proof to checkCheck the Python documentation for the standard features and constraints you use
What the guide addsthe comparison table, CSV example, and first-script checklist

Use the table to choose the smallest useful test before deciding whether to buy anything.

Links and disclosure

You can try this guide without purchasing a product. This page has no product purchase link; use the reference sources to check current requirements. Ad/PR is disclosed, and the page avoids exaggerated claims or income guarantees.

Reference sources

Browse all guides