Python is useful for small data-processing and automation jobs. In this beginner example, a script reads student scores from a CSV file, checks the input, and prints the number of students, average score and number who passed. It uses only Python's standard library, so no extra package installation is needed.
1. Prepare your project folder
Install Python 3 from python.org, then check your terminal:
python --versionSome systems use python3 instead of python. On Windows, the py launcher may also be available. Use the same interpreter consistently for the commands below. Create a folder named python-csv-demo and keep both files in it.
2. Save students.csv
name,score
Asha,42
Ravi,78
Meera,90The first row names the columns. This demonstration treats a score of 60 or more as a pass. Each score must be an integer between 0 and 100.
3. Save summarize_scores.py
import csv
from pathlib import Path
def summarize(path):
scores = []
with Path(path).open(encoding="utf-8-sig", newline="") as source:
reader = csv.DictReader(source)
if not {"name", "score"}.issubset(reader.fieldnames or []):
raise ValueError("CSV must contain name and score columns.")
for row in reader:
try:
score = int(row["score"])
except (TypeError, ValueError) as exc:
raise ValueError(
f"Invalid score at CSV line {reader.line_num}."
) from exc
if not 0 <= score <= 100:
raise ValueError(
f"Score outside 0..100 at CSV line {reader.line_num}."
)
scores.append(score)
if not scores:
raise ValueError("CSV has no score rows.")
return len(scores), sum(scores) / len(scores), sum(s >= 60 for s in scores)
if __name__ == "__main__":
try:
count, average, passed = summarize("students.csv")
print(f"Students: {count}")
print(f"Average: {average:.1f}")
print(f"Passed: {passed}")
except (OSError, ValueError) as exc:
raise SystemExit(str(exc))
4. Run the script from that folder
python summarize_scores.pyFor the sample above, the output is:
Students: 3
Average: 70.0
Passed: 2The average is 210 divided by 3. The formatting expression average:.1f displays one digit after the decimal point; it does not change the stored numeric value.
Understand the pieces
- DictReader turns each record into a dictionary whose keys come from the header.
- The with block closes the file when reading finishes or an error occurs.
- newline="" lets the CSV reader handle line endings. utf-8-sig also accepts a UTF-8 byte-order mark sometimes added by export tools.
- CSV values arrive as strings, so the script converts the score explicitly.
- The summarize function returns three values; the caller unpacks and displays them.
Try the validation
Change one score to abc: the program should report an invalid score and its CSV line number. Change it to 120: the range check should reject it. A file containing only the header should report that no score rows were found. Missing required columns should produce the header message.
The name column is required as part of this input format, but this first example does not validate individual names. Large input files may call for running totals instead of retaining every score in a list.
What to try next
Add a minimum and maximum score to the summary, or write the result to a separate CSV file. For projects that later need external packages, keep dependencies in a virtual environment.
The sample was run with Python 3.13.4. It is a local data-processing script; it does not upload the CSV anywhere.
Reference
Python documentation: CSV file reading and writing.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.