Python CSV Has No Attribute 'Writer'

Interrupt picture Interrupt · Aug 6, 2013 · Viewed 29.4k times · Source

There's a bit of code giving me trouble. It was working great in another script I had but I must have messed it up somehow.

The if csv: is primarily because I was relying on a -csv option in an argparser. But even if I were to run this with proper indents outside the if statement, it still returns the same error.

import csv

if csv:
    with open('output.csv', 'wb') as csvfile:
        csvout = csv.writer(csvfile, delimiter=',',
            quotechar=',', quoting=csv.QUOTE_MINIMAL)
        csvout.writerow(['A', 'B', 'C'])
        csvfile.close()

Gives me:

Traceback (most recent call last):
  File "import csv.py", line 34, in <module>
    csvout = csv.writer(csvfile, delimiter=',',
AttributeError: 'str' object has no attribute 'writer'

If I remove the if statement, I get:

Traceback (most recent call last):
  File "C:\import csv.py", line 34, in <module>
    csvout = csv.writer(csvfile, delimiter=',',
AttributeError: 'NoneType' object has no attribute 'writer'

What silly thing am I doing wrong? I did try changing the file name to things like test.py as I saw that in another SO post, didn't work.

Answer

thameera picture thameera · Jul 4, 2014

For me I had named my file csv.py. So when I import csv from that file I was essentially trying to import the same file itself.