0

I am trying to export some data to csv and I am trying this code


import csv

nms = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]

f = open('numbers2.csv', 'w')

with f:

    writer = csv.writer(f)

    for row in nms:
        writer.writerow(row)

but it returns this error:

  File "C:/Users/ASUS/Desktop/csv.py", line 3, in <module>
    import csv
  File "C:/Users/ASUS/Desktop\csv.py", line 11, in <module>
    writer = csv.writer(f)
AttributeError: module 'csv' has no attribute 'writer' ```
Any help???
  • 2
    You named your script "csv.py", masking the `csv` module. You are importing your own script. Just rename your script to something else. – tdelaney May 08 '20 at 22:33

2 Answers2

1

When a module is missing a well-defined variable, its good to ask whether you've really imported the right module. You can print(csv.__file__) to see whether you got the right thing.

Python has a rule that it will add a script's directory to the module search path so that it can find other modules you may be using in your project. One downside is that if you have a module with the same name as an installed module, your local module wins.

From the traceback its easy to see the problem. Your script is File "C:/Users/ASUS/Desktop/csv.py". Since you named your script "csv.py", it was imported instead of the standard module. The solution is to name your .py file something else.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

I've runned you code using python 3.8.2 and it wok's well. If you are using an old python version try to install the last version, available here.

to check you python's version, type:

pythnon --version
morallito
  • 109
  • 1
  • 10