python-for-j277 / files · Lesson 15
Lesson 15 — Files
CSV File Handling
Work with comma-separated data, like a simple spreadsheet.
A CSV file (comma-separated values) stores rows of data, with commas between the fields. It is the plain-text cousin of a spreadsheet.
What a CSV looks like
students.csv
Ava,15,Blue Ben,14,Green Cara,16,Red
Each line is one record; each value is separated by a comma. Here the fields are name, age and favourite colour.
Writing a CSV
file = open("students.csv", "w")
file.write("Ava,15,Blue\n")
file.write("Ben,14,Green\n")
file.write("Cara,16,Red\n")
file.close()How it works
- A CSV is just a text file, so we use the same
open,writeandclose. - Put commas between the fields and
\nat the end of each record.
Reading and splitting each line
file = open("students.csv", "r")
for line in file:
line = line.strip()
fields = line.split(",")
print(fields[0], "is", fields[1], "years old")
file.close()Output
Ava is 15 years old Ben is 14 years old Cara is 16 years old
How it works
- We read the file one line at a time.
.strip()removes the newline from the end of the line..split(",")breaks the line into a list of fields at each comma.fields[0]is the first value,fields[1]the second, and so on.
Fields are an array
split(",") gives you a 1-D array of the fields, so everything you learned about arrays applies here.Everything read is textEvery field read from a file is a string. Cast with
int(fields[1]) if you need to do maths with it.The CSV recipeReading a CSV is 'read a line, strip it, split it on commas' — then use the fields by index.
What you have learned
- A CSV stores records, one per line, with commas between fields.
- It is an ordinary text file, so
open,writeandclosestill apply. .split(",")turns a line into a list of fields.- Fields are text — cast them if you need numbers.