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:
import csvLeave it out and the first call fails with a message that names it:
f = open('marks.csv', 'w', newline='')
w = csv.writer(f)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'?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 → lineGive it the open file. It gives back a writer object, whose job is to put rows in.
csv.reader(f)line → listGive 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.
import csv
f = open('marks.csv', 'r', newline='')
r = csv.reader(f)
print(r)
f.close()<_csv.reader object at 0x7d88786557e0>
<_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:
import csvonce, at the topf = open('marks.csv', 'w', newline='')the ordinary open() you already knoww = csv.writer(f)wrap the file — this is the only new linef.close()close the FILE, not the writer4Why 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:
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()['Sharma', ' Kumar and Sons', 'Delhi']
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()"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",DelhiThe 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.
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:
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
| pickle | csv | |
|---|---|---|
| Import | import pickle | import csv |
| File mode | 'wb' / 'rb' — binary | 'w' / 'r' — text |
| Writing | pickle.dump(obj, f) | w = csv.writer(f), then w.writerow(row) |
| Reading | obj = pickle.load(f) | r = csv.reader(f), then loop over r |
| What comes back | the object, with its type | a list of strings, always |
| Who else can read the file | only Python | anything at all |
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
Standard library. Nothing to install, lowercase name, one line at the top.
Wraps an open file and gives back a writer object. Its methods put rows in.
Wraps an open file and gives back a reader object. Loop over it to take rows out.
open() first, always. The module never opens anything.
A writer has no close(). Closing the file it wraps is what finishes the job.
A value containing a comma is wrapped in quotes on the way out and unwrapped on the way back.
- 1
Print a
csv.readerobject 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
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
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.
What does csv.writer() take as its argument?
How do you finish with a csv writer when you are done?
Your file contains the line "Rao, Jr",Delhi. How many values does csv.reader() give back for it?
After reading a row with csv.reader(), what type is every value in it?