📊 We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 4 · Lesson 11 of 15

0% Exit to course

Module 4 · Files and real data Lesson 11 of 15

CSV — the format every office runs on

Learning objective

CSV is plain text with commas: the format of exports from Excel, Google Sheets and almost every college and office system.

The concept

CSV is a plain text file where each line is a row and commas separate the fields. It is what Excel, Google Sheets, banking portals and college systems export, which is why it is the first data format worth knowing — not because it is clever, but because everything ends up in it.

import csv then csv.reader(f) gives you one list per row, so row[0] is the first column and row[2] the third. When the file has a header, csv.DictReader(f) is better: every row arrives as a dictionary keyed by the column names, so you write row["city"] instead of counting commas and hoping. Read the header row first and print it — you are then certain which column is which before you write any logic.

Python
import csv

with open("students.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["city"])   # keyed by the header row

Common mistakes

The mistake is assuming the file is clean: extra blank lines, extra spaces after commas, amounts written as "1,200" with a comma inside the field, and one stray semicolon instead of a comma will all break a loop. Print the first five rows before writing anything clever, and count the columns in each — that five-second check is what separates someone who debugs for an hour from someone who does not.

Worked example

import csv then csv.reader(f) gives one list per row, so row[0] is the first column — exactly how a marks or attendance sheet is structured.

Your practice task

Export any real spreadsheet to CSV, read it in Python, and print the number of rows and the column names.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

CSV is a plain text file where each line is a row and commas separate the fields.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.