Lesson 5 of 5 · Errors and Files · 4 min read · Updated

CSV and binary files

Reading and writing spreadsheet-style data safely, and files that hold bytes rather than text.

Splitting lines on commas by hand breaks the moment a value contains a comma — an address such as "Chennai, TN". The standard csv module handles quoting for you.

python
import csv

with open("places.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerow(["Kavya", "Chennai, TN"])

with open("places.csv", encoding="utf-8") as f:
    print(f.read().strip())

with open("places.csv", newline="", encoding="utf-8") as f:
    print(next(csv.reader(f)))
Output
Kavya,"Chennai, TN"
['Kavya', 'Chennai, TN']

The writer put quotes around the value with a comma; the reader took them off again and gave back exactly two fields. Open CSV files with newline="" — the csv module manages line endings itself, and without it Windows gets blank lines between rows.

Rows as dictionaries

python
import csv

students = [{"name": "Meena", "marks": 94}, {"name": "Ravi", "marks": 66}]
with open("marks.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "marks"])
    writer.writeheader()
    writer.writerows(students)

with open("marks.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], int(row["marks"]) + 5)
Output
Meena 99
Ravi 71

Note

DictReader uses the header row as keys, so the code reads row["marks"] rather than row[1], and survives someone adding a column. Every value comes back as text — convert numbers with int() or float(). A CSV file saved this way opens directly in Excel.

Binary files

python
data = "வணக்கம்".encode("utf-8")
print(type(data).__name__, len(data), len("வணக்கம்"))

with open("greeting.bin", "wb") as f:
    f.write(data)

with open("greeting.bin", "rb") as f:
    raw = f.read()

print(raw[:3])
print(raw.decode("utf-8"))
Output
bytes 21 7
b'\xe0\xae\xb5'
வணக்கம்

Images, PDFs and ZIP files are not text, so they are opened in binary mode — "rb" and "wb" — and give bytes instead of strings. Text itself is stored as bytes: encode() turns a string into bytes and decode() turns them back. Seven Tamil characters take 21 bytes in UTF-8.

python
# Copy any file — a photo, a PDF — in chunks, so even a huge file fits in memory
with open("photo.jpg", "rb") as source, open("photo-copy.jpg", "wb") as target:
    while chunk := source.read(64 * 1024):
        target.write(chunk)

Note

Binary mode takes no encoding — there is no text to decode. The := ("walrus") operator assigns and tests in one step: read a chunk, and stop when it comes back empty.

Which mode opens an image for reading?

Try this now

  1. Write five students' names, cities and marks to a CSV file with DictWriter, open it in Excel, then read it back and print the top scorer.
  2. Write a program that copies any file given its name, using binary mode, and prints how many bytes it copied.

Create a free account to save your progress, or sign in.