LambdaLabTM
Computer Science · Class 12 · CSV Files
CSV filesimport csv⏱️ 11 min read

The csv Module

One import, and two objects for the rest of the chapter. A writer turns a list into a line of the file, and a reader turns a line of the file back into a list. Neither of them opens or closes anything — that is still your job, and it is the part students forget first.

1import csv

csv is a standard library module — it comes with Python, exactly like pickle, math and random. There is nothing to download and no pip install to run. One line at the top of the program:

importing.py
import csv

Leave it out and the first call fails with a message that names it:

forgot_import.py
f = open('marks.csv', 'w', newline='')
w = csv.writer(f)
Output
Traceback (most recent call last):
  File "forgot_import.py", line 2, in <module>
    w = csv.writer(f)
NameError: name 'csv' is not defined. Did you forget to import 'csv'?
Note
The name in the import is lowercase — csv, not CSV. Python is case sensitive about module names, and import CSV gives you ModuleNotFoundError: No module named 'CSV'.

2The two things the module makes

csv.writer(f)list → line

Give it the open file. It gives back a writer object, whose job is to put rows in.

csv.reader(f)line → list

Give it the open file. It gives back a reader object, which you loop over to take rows out.

Both take the same one argument: a file that open() has already handed back. Not a filename — the file object itself.

wrapping.py
import csv

f = open('marks.csv', 'r', newline='')

r = csv.reader(f)
print(r)

f.close()
Output
<_csv.reader object at 0x7d88786557e0>
A reader is not a list
Printing it gives you that <_csv.reader object> line, not your data — the same surprise range() gave you in Class 11. To see the rows you loop over it, which is the reading lesson.

3The module never opens the file

This is the single most common misunderstanding on the topic. There is no csv.open(). The pattern is always four steps, in this order:

1
import csvonce, at the top
2
f = open('marks.csv', 'w', newline='')the ordinary open() you already know
3
w = csv.writer(f)wrap the file — this is the only new line
4
f.close()close the FILE, not the writer
Key Takeaway
A writer or a reader has no close method of its own. There is nothing to close: it is a wrapper around a file, and closing the file is what finishes the job.

4Why not just use split() and join()?

For simple data you genuinely could, and the previous lesson did. The module earns its place on the values that are not simple. Here is one row, written both ways, with a name that happens to contain a comma:

by_hand_again.py
f = open('shops.csv', 'w')
f.write('Sharma, Kumar and Sons,Delhi\n')
f.close()

f = open('shops.csv', 'r')
for line in f:
    print(line.strip().split(','))
f.close()
Output
['Sharma', ' Kumar and Sons', 'Delhi']
with_the_module.py
import csv

f = open('shops.csv', 'w', newline='')
w = csv.writer(f)
w.writerow(['Sharma, Kumar and Sons', 'Delhi'])
f.close()

f = open('shops.csv', 'r', newline='')
print(f.read())
f.close()

f = open('shops.csv', 'r', newline='')
for row in csv.reader(f):
    print(row)
f.close()
Output
"Sharma, Kumar and Sons",Delhi

['Sharma, Kumar and Sons', 'Delhi']
w.writerow(['Sharma, Kumar and Sons', 'Delhi'])

Two values handed over. The writer noticed the comma inside the first one and wrapped that value in double quotes on its own initiative.

"Sharma, Kumar and Sons",Delhi

The line in the file. Three commas are visible, but only the one outside the quotes is a separator.

for row in csv.reader(f)

The reader knows the same rule and unwraps it: two values back, and the quotes are gone because they were never part of the value.

Key Takeaway
The quotes are punctuation the file uses, not part of your data. You never type them and never strip them — the writer adds them when they are needed, and the reader removes them again.

5Everything comes back as text

One thing the module does not do for you. Numbers go in without a str(), which feels like magic — but they do not come back out as numbers:

still_strings.py

The row comes back as ['1', 'Ravi', '78'] — three strings. That is not the module being careless. A CSV file is text, and text is all it can store, so the int() on the way back is still your job. The reading lesson spends a whole section on it.

6Set beside the pickle module

Let's Recap!
picklecsv
Importimport pickleimport csv
File mode'wb' / 'rb' — binary'w' / 'r' — text
Writingpickle.dump(obj, f)w = csv.writer(f), then w.writerow(row)
Readingobj = pickle.load(f)r = csv.reader(f), then loop over r
What comes backthe object, with its typea list of strings, always
Who else can read the fileonly Pythonanything at all
pickle works in one step, csv in two
pickle.dump() is a function you call on the module. csv.writer() is not — it builds an object, and that object has the method that writes. Writing csv.writerow(row, f) is the mistake this difference causes, and it fails with AttributeError: module 'csv' has no attribute 'writerow'. Did you mean: 'writer'?

7Recap

import csv

Standard library. Nothing to install, lowercase name, one line at the top.

csv.writer(f)

Wraps an open file and gives back a writer object. Its methods put rows in.

csv.reader(f)

Wraps an open file and gives back a reader object. Loop over it to take rows out.

Both take a file, not a filename

open() first, always. The module never opens anything.

Close the file, not the writer

A writer has no close(). Closing the file it wraps is what finishes the job.

Quoting is handled for you

A value containing a comma is wrapped in quotes on the way out and unwrapped on the way back.

✍️ Now write these yourself
  1. 1

    Print a csv.reader object without looping over it, and read what Python says.

    Hint · <_csv.reader object at …>. The hex number will differ from the one above — it is an address in memory.

  2. 2

    Try csv.writerow([1, 2], f) on purpose and read the error.

    Hint · The module has no such attribute. The method belongs to the writer object, not to csv.

  3. 3

    Write a row containing 'Delhi, India' and open the file in Notepad.

    Hint · The quotes you never typed are in the file. That is the module at work.

Quick Check

What does csv.writer() take as its argument?

Quick Check

How do you finish with a csv writer when you are done?

Quick Check

Your file contains the line "Rao, Jr",Delhi. How many values does csv.reader() give back for it?

Quick Check

After reading a row with csv.reader(), what type is every value in it?