Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

python - CSV Module AttributeError

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...