Question

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.

Was it helpful?

Solution 2

If you've set something that assigns to csv (looks like a string) then you're shadowing the module import. So, the simplest thing is to just change whatever's assigning to csv that isn't the module and call it something else...

In effect what's happening is:

import csv
csv = 'bob'
csvout = csv.writer(somefile)

Remove the further assignment to csv and go from there...

OTHER TIPS

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.

For my case, my function name happened to be csv(). Once I renamed my function, the error disappeared.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top