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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With