24

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

2
  • 3
    also make sure you delete (if present) any csv.pyc file that may have been created on import Commented Mar 14, 2012 at 23:33
  • 1
    Had the same error, for same reason Commented Feb 7, 2015 at 17:32

2 Answers 2

94

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I had the same error. But after I changed the name of the file I had to remove the csv.pyc from the working folder.
3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.