Kids Coding
Files and CSV
Read rows from a CSV-style file. Total a column. Print a clean summary.
Rows of text
CSV is a common file shape: commas between fields, one row per line. You can write it as text, then split.
Write and total
text = "Sam,12\nRiley,8\nJun,15\n"
with open("scores.csv", "w", encoding="utf-8") as file:
file.write(text)
total = 0
with open("scores.csv", "r", encoding="utf-8") as file:
for line in file:
line = line.strip()
if not line:
continue
name, score = line.split(",")
total = total + int(score)
print(name, score)
print("Total:", total)Every value read from a file arrives as text. Turn "42" into a number with int(...) before you do maths, or "42" + "1" becomes "421" instead of 43.
strip and split
strip()removes the newline.split(",")turns a line into a list.int(...)turns the score into a number you can add.
Real life
An attendance file the teacher exports: name, comma, present or absent.
Split on the comma. Count who showed up. That is a CSV in real school software.
Attendance
lines = ["Sam,yes", "Riley,no", "Jun,yes"]
present = 0
for line in lines:
name, here = line.split(",")
if here == "yes":
present = present + 1
print(name, "is here")
print("Present:", present)Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Split "Sam,12" on a comma and print the name.
Show solution
name, score = "Sam,12".split(",")
print(name)