Python Series track

Project 14 · Practice Projects

Project 14 — CSV Report CLI

Analyse a CSV file from the command line: filter rows, compute statistics, and generate HTML and Markdown reports using Pandas and Jinja2 templates.

Practice Projects1 min readFree lesson

Difficulty: Lv ★★★★ | Prerequisites: Advanced Week 8 (or Intermediate Week 6)

Goal

Receive a CSV file and automatically generate a statistical report

Requirements

  • Input: python solution.py sales.csv
  • Automatic column detection → Numbers: Average/Maximum/Minimum/Sum, Text: Top 5 frequency
  • Display results on both the console and report.txt

Challenge Task

  • Filter options (--column price --min 10000)
  • matplotlib PNG

Assignment

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution.pyPython
"""Automatic CSV Analysis — Using Only the Standard CSV Module"""
import csv
import sys
from collections import Counter
from pathlib import Path

def is_number(s):
    try:
        float(s); return True
    except ValueError:
        return False

def analyze(path):
    with open(path, encoding="utf-8") as f:
        reader = csv.DictReader(f)
        rows = list(reader)
        cols = reader.fieldnames

    if not rows:
        return ["(empty file)"]

    out = [f"[Number of rows] {len(rows)}"]

    for col in cols:
        values = [r[col] for r in rows if r[col] != ""]
        if not values: continue

        if all(is_number(v) for v in values):
            nums = [float(v) for v in values]
            out.append(f"[Number: {col}]")
            out.append(f"Average: {sum(nums) / len(nums):,.2f}")
            out.append(f"Maximum: {max(nums):,.2f}")
            out.append(f"Minimum: {min(nums):,.2f}")
            out.append(f"Sum: {sum(nums):,.2f}")
        else:
            counter = Counter(values)
            out.append(f"[Text: {col}]")
            for val, cnt in counter.most_common(5):
                out.append(f"  {val:<20} {cnt:>6}")

    return out

def main():
    if len(sys.argv) != 2:
        print("Usage: python solution.py <csv file>")
        sys.exit(1)
    path = Path(sys.argv[1])
    if not path.exists():
        print(f"File not found: {path}")
        sys.exit(1)

    result = analyze(path)
    text = "\n".join(result)
    print(text)
    Path("report.txt").write_text(text, encoding="utf-8")
    print("Saved to report.txt")

if __name__ == "__main__":
    main()

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now