Python csv import fails

2019-02-27 15:27发布

So I'm trying to use the csv module in python 3.3.2 but I am getting this error.

    Traceback (most recent call last):
      File "C:\Users\massi_000\Desktop\csv.py", line 1, in <module>
         import csv
      File "C:\Users\massi_000\Desktop\csv.py", line 4, in <module>
        csv.reader(f)
    AttributeError: 'module' object has no attribute 'reader'

Obviously I'm going something stupendously wrong but all the code I am using is below and it looks fine. Has something changed in this version that has rendered this code unusable or..?

import csv
f = open("test.csv")
csv.reader(f)
for row in csv_fi:
    print(row)
f.close()

2条回答
啃猪蹄的小仙女
2楼-- · 2019-02-27 16:10

You have named your file csv.py and this clashes with the csv module from the Python standard library.

You should rename your own file to something else so that import csv will import the standard library module and not your own. This can be confusing but this is a good rule-of-thumb going forward: avoid giving your own Python files names that are the same as modules in the standard library.

查看更多
Bombasti
3楼-- · 2019-02-27 16:19

As @Simeon Visser said, you have to rename your file but you have some other issues with your code as well. Try this:

import csv
with open('test.csv', newline='') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        print (', '.join(row))
查看更多
登录 后发表回答