1. Start with an empty folder
CSV stores a table as text: commas separate fields and new lines separate records. JSON is a text format with named fields. The product takes demo.csv as input and creates summary.json, where you can inspect the totals for each project.
You need Python 3 and a plain-text editor. Run python3 --version in your terminal. If the command is unavailable, install Python 3 and reopen the terminal. The recorded run used Python 3.14.4. No extra packages, accounts or network calls are needed.
Create a folder named csv-basliq-v1. The tree below shows the three files you will create; do not save the tree itself as a file. Use UTF-8 and avoid hidden .txt extensions. Do not create summary.json manually: the program will create it.
csv-basliq-v1/
app.py
demo.csv
test_app.py
2. Create app.py to select named columns
Copy the complete code into app.py. summarize reads the header first, then locates the columns named project and units. Adding user_id at the start therefore leaves the calculation unchanged; the extra column is not copied into the output.
Each row needs a project name and a nonnegative whole count. Quotes, duplicate headers and field counts are also checked. Only after validating the whole input does the app write a new output file. The x mode refuses to replace an existing file.
"""Summarize synthetic project/units CSV using header names."""
import argparse
import csv
import io
import json
import sys
MAX_BYTES = 1024 * 1024
MAX_UNITS = 1_000_000_000
MAX_TOTAL = 1_000_000_000_000
def check_quotes(text):
# CSV quotes must surround a whole field; doubled quotes escape a quote.
state = "start"
for char in text:
if state == "quoted":
if char == '"':
state = "closed"
elif state == "closed":
if char == '"':
state = "quoted"
elif char in ",\r\n":
state = "start"
else:
raise ValueError("Malformed CSV quotes")
elif char in ",\r\n":
state = "start"
elif char == '"':
if state != "start":
raise ValueError("Malformed CSV quotes")
state = "quoted"
else:
state = "plain"
if state == "quoted":
raise ValueError("Malformed CSV quotes")
def summarize(path):
with open(path, "rb") as source:
raw = source.read(MAX_BYTES + 1)
if len(raw) > MAX_BYTES:
raise ValueError("Input exceeds 1 MiB")
text = raw.decode("utf-8-sig")
check_quotes(text)
reader = csv.reader(io.StringIO(text, newline=""), strict=True)
headers = next(reader, [])
if len(set(headers)) != len(headers):
raise ValueError("Duplicate headers")
if "project" not in headers or "units" not in headers:
raise ValueError("Required headers: project,units")
project_col, units_col = headers.index("project"), headers.index("units")
projects, total, count = {}, 0, 0
for row in reader:
if len(row) != len(headers):
raise ValueError("Row field count does not match headers")
project, units = row[project_col].strip(), row[units_col]
if not project or len(project) > 100:
raise ValueError("Project must contain 1 to 100 characters")
if not units or len(units) > 10 or not units.isascii() or not units.isdigit():
raise ValueError("Units must be a nonnegative integer")
amount = int(units)
if amount > MAX_UNITS or total + amount > MAX_TOTAL:
raise ValueError("Units limit exceeded")
projects[project] = projects.get(project, 0) + amount
total += amount
count += 1
return {"projects": projects, "rows": count, "total_units": total}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", help="UTF-8 CSV file")
parser.add_argument("output", help="New JSON file; must not exist")
args = parser.parse_args()
try:
result = summarize(args.input)
payload = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
with open(args.output, "x", encoding="utf-8", newline="\n") as target:
target.write(payload)
except (OSError, ValueError, csv.Error) as error:
print(f"Error: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
3. Save the small table as demo.csv
Save the complete data below as demo.csv. Atlas and Orion are invented project names; 101, 102 and 103 are demo identifiers. units is a simple count, not a price or an academy result. Notice that units appears before project in the header.
The expected calculation is 3 plus 4 for Atlas, giving 7; Orion stays at 2. There are three data rows and a total of 9 units. Those numbers describe only this sample input. Hardcoding column positions could produce a wrong calculation after adding a column.
user_id,units,project
101,3,Atlas
102,2,Orion
103,4,Atlas
4. Run the app and check empty and invalid input
Open a terminal in the folder and run python3 app.py demo.csv summary.json. Success prints nothing. Open summary.json: projects should contain Atlas 7 and Orion 2, with rows 3 and total_units 9. Repeating the command gives an Error message and preserves the existing result. Use a new output filename for another run.
Create empty.csv containing only project,units followed by a line ending. Run python3 app.py empty.csv empty.json. Expect empty projects, rows 0 and total_units 0. A completely empty file lacks the required headers and should instead produce an error.
In bad.csv, put project,units on the first line and Atlas,-1 on the second. Run python3 app.py bad.csv bad.json. Expect Error: Units must be a nonnegative integer and no bad.json. Change -1 to 1 and try again. You do not need to delete an existing file; use a fresh output name for each successful run.
5. Verify behavior with test_app.py
Save the complete test code as test_app.py. It checks the results and the response to bad input. Run python3 -m unittest -v test_app.py in the terminal. The supplied product passed 3 test groups; you should see Ran 3 tests and OK.
The tests launch the actual program in a separate process. They check changed column order and extra columns, empty tables, quotes, size and count limits, and preservation of input and output files. If you do not get OK, first check that all three files are together and their code is complete.
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import app
class CsvTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.source = Path(self.temp.name) / "input.csv"
self.output = Path(self.temp.name) / "output.json"
def write(self, text):
self.source.write_text(text, encoding="utf-8")
def cli(self, output=None):
return subprocess.run(
[sys.executable, str(Path(app.__file__)), str(self.source),
str(self.output if output is None else output)],
capture_output=True, text=True, timeout=5)
def test_demo_and_existing_files(self):
self.write("\ufeffuser_id,units,project\n1,3,Atlas\n2,2,Orion\n3,4,Atlas\n")
original = self.source.read_bytes()
self.assertEqual(self.cli().returncode, 0)
expected = {"projects": {"Atlas": 7, "Orion": 2}, "rows": 3, "total_units": 9}
self.assertEqual(json.loads(self.output.read_text()), expected)
saved = self.output.read_bytes()
self.assertNotEqual(self.cli().returncode, 0)
self.assertEqual(self.output.read_bytes(), saved)
self.assertNotEqual(self.cli(self.source).returncode, 0)
self.assertEqual(self.source.read_bytes(), original)
def test_empty_and_quoted(self):
self.write("project,units\n")
self.assertEqual(app.summarize(self.source),
{"projects": {}, "rows": 0, "total_units": 0})
self.write('project,units\r\n"A, \"\"B\"\"",0\r\n')
self.assertEqual(app.summarize(self.source)["projects"], {'A, "B"': 0})
def test_invalid_cli_never_creates_output(self):
cases = ["", "project\nA\n", "project,units,units\nA,1,2\n",
"project,units\nA\n", "project,units\nA,1,extra\n",
"project,units\n\n", "project,units\n ,1\n",
"project,units\n" + "A" * 101 + ",1\n",
'project,units\n"A,1\n', 'project,units\nA"B,1\n',
'project,units\n"A"x,1\n',
"project,units\n" + "A,1000000000\n" * 1001]
cases += ["project,units\nA," + n + "\n"
for n in ["", "-1", "1.5", "+1", " 1", "١", "1000000001"]]
for text in cases:
with self.subTest(text=text):
self.write(text)
result = self.cli()
self.assertEqual(result.returncode, 1)
self.assertIn("Error:", result.stderr)
self.assertFalse(self.output.exists())
for raw in [b"\xff", b"x" * (app.MAX_BYTES + 1)]:
self.source.write_bytes(raw)
self.assertEqual(self.cli().returncode, 1)
self.assertFalse(self.output.exists())
if __name__ == "__main__":
unittest.main()
6. Give your product a different input
Exercise: copy demo.csv, change the header to project,user_id,units and move every row into that order. Convert the copy to a new JSON filename. Expect Atlas 7, Orion 2 and total 9 again. Then add a row for Atlas with units 1: expect Atlas 8, rows 4 and total_units 10.
Input is limited to 1 MiB. Project names use 1–100 characters, each row permits at most one billion units and the total is limited to one trillion. Only comma-separated UTF-8 input is supported; an Excel workbook cannot be opened directly. This is not a complete GitHub report integration. A disk write failure may leave a partial new file; existing files are not replaced.

