45 — CSV: rows of data
A CSV file is plain text — one row per line, fields separated by commas; a small file only needs split(",").
Steps
Create
data.csvwith onename,scorerow per line:
run it →Mina,90 Yuna,70 Sora,85 Jun,75Read the file and cut it into rows:
splitlines()splits the text into lines, andline.split(",")splits one row into fields:
run it →use file latest lines = file_read("data.csv").splitlines() parts = lines[0].split(",") show parts[0] show int(parts[1])Total the scores and divide by the row count for the average. Save it as
scores.nme— it collects every row and writes a summary:
run it →# scores.nme — read a CSV, average the score column, write a summary. # Run: nme r scores use file latest raw = file_read("data.csv") lines = raw.splitlines() names = [] scores = [] for line in lines: parts = line.split(",") names.append(parts[0]) scores.append(int(parts[1])) total = 0 biggest = scores[0] for score in scores: total = total + score if score > biggest: biggest = score average = total / len(scores) show f"Read {len(lines)} rows from data.csv" for i in range(len(names)): show f"{names[i]}: {scores[i]}" show f"Total: {total}" show f"Average: {average}" show f"Highest: {biggest}" summary = f"rows,{len(lines)}\ntotal,{total}\naverage,{average}\nhighest,{biggest}\n" file_write("summary.csv", summary) show "Wrote summary.csv"Run it next to
data.csv, then look at the newsummary.csv:nme r scoresRead 4 rows from data.csv Mina: 90 Yuna: 70 Sora: 85 Jun: 75 Total: 320 Average: 80.0 Highest: 90 Wrote summary.csvrows,4 total,320 average,80.0 highest,90
Try it yourself
Track the lowest score too — a lowest = scores[0] start, an if score < lowest check, and a lowest,<value> line in summary.
What you learned
file_read(...).splitlines()cuts a file into rows.line.split(",")splits a row into fields;parts[1]is the second field.int(parts[1])turns text into a number before adding.file_writewrites the summary back out as CSV.