简体   繁体   English

Python CSV导入失败

[英]Python csv import fails

So I'm trying to use the csv module in python 3.3.2 but I am getting this error. 因此,我尝试在python 3.3.2中使用csv模块,但出现此错误。

    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()

You have named your file csv.py and this clashes with the csv module from the Python standard library. 您已将文件命名为csv.py ,这与Python标准库中的csv模块冲突。

You should rename your own file to something else so that import csv will import the standard library module and not your own. 您应该将自己的文件重命名为其他文件,以便import csv将导入标准库模块而不是您自己的模块。 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. 这可能会造成混淆,但这是一个很好的经验法则:避免给自己的Python文件起一个与标准库中的模块相同的名称。

As @Simeon Visser said, you have to rename your file but you have some other issues with your code as well. 正如@Simeon Visser所说,您必须重命名文件,但是代码也有其他问题。 Try this: 尝试这个:

import csv
with open('test.csv', newline='') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        print (', '.join(row))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM