Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV Module AttributeError

Tags:

So I copied and pasted a demo program from the book I am using to learn Python:

#!/usr/bin/env python     import csv total = 0 priciest = ('',0,0,0) r = csv.reader(open('purchases.csv')) for row in r:     cost = float(row[1]) * float(row[2])     total += cost     if cost == priciest[3]:         priciest = row + [cost] print("You spent", total) print("Your priciest purchase was", priciest[1], priciest[0], "at a total cost of", priciest[3]) 

And I get the Error:

Traceback (most recent call last):       File "purchases.py", line 2, in <module>         import csv       File "/Users/Solomon/Desktop/Python/csv.py", line 5, in <module>         r = csv.read(open('purchases.csv')) AttributeError: 'module' object has no attribute 'read' 

Why is this happening? How do I fix it? Update: Fixed All The Errors Now I'm getting:

Traceback (most recent call last):   File "purchases.py", line 6, in <module>     for row in r: _csv.Error: line contains NULL byte 

What was happening in terms of the CSV.py: I had a file with the same code named csv.py, saved in the same directory. I thought that the fact that it was named csv .py was screwing it up, so I started a new file called purchases.py, but forgot to delete csv

like image 650
Billjk Avatar asked Mar 14 '12 23:03

Billjk


2 Answers

Don't name your file csv.py.
When you do, Python will look in your file for the csv code instead of the standard library csv module.

Edit: to include the important note in the comment: if there's a csv.pyc file left over in that directory, you'll have to delete that. that is Python bytecode which would be used in place of re-running your csv.py file.

like image 147
mechanical_meat Avatar answered Sep 18 '22 12:09

mechanical_meat


There is a discrepancy between the code in the traceback of your error:

r = csv.read(open('purchases.csv')) 

And the code you posted:

r = csv.reader(open('purchases.csv')) 

So which are you using?

At any rate, fix that indentation error in line 2:

#!/usr/bin/env python import csv total = 0 

And create your csv reader object with a context handler, so as not to leave the file handle open:

with open('purchases.csv') as f:   r = csv.reader(f) 
like image 31
wim Avatar answered Sep 21 '22 12:09

wim