In the previous steps, we stored plain text files, which work fine for simple notes. However, as our data becomes more structured — like a list of students with names, ages, and scores — plain text quickly becomes messy. This is where CSV files come in handy.
CSV stands for Comma-Separated Values. It’s a simple text format where each line represents a record and each field is separated by a comma. For example:
name,age,score
Alice,12,89
Bob,13,95
Cindy,11,82
It looks like a table, and indeed most spreadsheet programs (like Excel or Google Sheets) can open it directly. Python includes a built-in csv module that makes writing and reading such files very easy. Let’s start with a simple example.
Example A:
import csv
students = [
["name", "age", "score"],
["Alice", 12, 89],
["Bob", 13, 95],
["Cindy", 11, 82]
]
with open("students.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(students)
print("Saved to students.csv")
After running this, you’ll see a file named students.csv. Open it, and you’ll see a neat table. Note that:
newline="" prevents extra blank lines on Windows;writer.writerows() writes multiple rows at once.CSV is essentially a structured text file, if we follow the comma rule ourselves, we could write it manually like Example B.
Example B:
with open("scores.csv", "w", encoding="utf-8") as f:
f.write("name,math,englishn")
f.write("Tom,85,78n")
f.write("Jerry,92,88n")
But using csv.writer is safer because it automatically handles commas and newlines inside text.
Now let’s try a small exercise: ask students to input several shopping items, including name, quantity, and price, and save them to shopping.csv
Output example:
Item name (0 to stop): Pencil
Quantity: 5
Price: 1.5
Item name (0 to stop): Notebook
Quantity: 2
Price: 3
Item name (0 to stop): 0
Shopping list saved to shopping.csv
Answer example:
import csv
items = []
while True:
name = input("Item name (0 to stop): ")
if name == "0":
break
qty = int(input("Quantity: "))
price = float(input("Price: "))
items.append([name, qty, price, qty * price])
with open("shopping.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Quantity", "Price", "Total"])
writer.writerows(items)
print("Shopping list saved to shopping.csv")
To conclude, CSV is the universal language of data, it bridges simple text and structured databases. In the next lesson, we will learn how to read and analyze CSV data back into Python for calculations and summaries.