CSV text and csv.reader
Split comma-separated lines into rows you can loop over.
CSV (comma-separated values) is the most common way to share tables. Each line is a row; commas separate the columns; the first line usually holds the column names. Python’s csv module reads it correctly, even tricky cases like a comma inside quotes. In this course the CSV is written right in the program as a string, and io.StringIO(text) makes that string behave like an open file. Every value comes back as text, so convert numbers yourself.
import csv, io
text = """fruit,boxes
apple,12
pear,7
"""
reader = csv.reader(io.StringIO(text))
header = next(reader)
for row in reader:
print(row[0], int(row[1]) * 2)next(reader) takes the first line (the header) off the top. Each remaining row is a list of strings like ["apple", "12"], so int(row[1]) converts the box count before doing math.
list(reader) gives all the remaining rows at once as a list of lists.
In real projects you would open a file with open("sales.csv"); io.StringIO lets us practice the same thing without files.