22

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.

3 Answers 3

75

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.

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

4 Comments

same for me too :-)
Same here ... (facepalm)
my face when ಥ_ಥ
facepalm-- @thameera thanks! changed my file to "not_csv.py" and now works perfectly :)
16

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...

1 Comment

You're right, I'm sorry for not seeing it sooner. I had a csv = args.csv elsewhere in the script. Thank you so much!! Changing the if statement to if args.csv and removing the previous csv = args.csv solved it. Excellent.
0

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

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.