Count CSV Rows

Count CSV Rows

Write a function that counts the data rows in a simple CSV file.

count_csv_rows(path)

The file has one row per line; the first line is a header and shouldn't be counted. Return the number of remaining (data) rows.

Examples

Given a file containing:

name,age
Ada,36
Alan,41

count_csv_rows(path) returns 2 (the header line doesn't count).


Walkthrough

Thinking it through

def count_csv_rows(path):
    with open(path) as f:
        lines = f.read().splitlines()
    return len(lines) - 1

f.read() gets the entire file as one string; .splitlines() breaks it into a list of lines, one per row, with the trailing \n characters already stripped off (unlike readlines(), which keeps them — splitlines() is usually the more convenient choice when you don't need to preserve the newlines themselves).

From there, the row count is just "total lines, minus the header" — len(lines) - 1. For the example file ("name,age\nAda,36\nAlan,41"), splitlines() gives ["name,age", "Ada,36", "Alan,41"] — three lines total, minus the header, is 2 data rows.

This problem is a simplified stand-in for real CSV parsing — Python's standard library actually has a dedicated csv module for handling quoted fields, embedded commas, and other edge cases a real CSV file might contain. For files this simple (no quoting, no embedded commas), splitting on lines and commas by hand is fine; for anything more complex, you'd reach for csv.reader instead of reinventing it.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.