Python学习中遇到的问题(更新)

最近在学习机器学习方面的知识,需要用到读取.csv文件中的数据

allElectronicsData = open(AllElectronics.csv, rb)
reader = csv.reader(allElectronicsData)
for item in reader:
    print(item)
headers = next(reader

然后在运行时就遇到了下面的错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:UsersThinkCentreAnaconda3libsite-packagesspyderutilssitesitecustomize.py", line 866, in runfile
    execfile(filename, namespace)
  File "D:UsersThinkCentreAnaconda3libsite-packagesspyderutilssitesitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, exec), namespace)
  File "C:/Users/ThinkCentre/Desktop/deep_learning/Dtree/AllElectronics.py", line 17, in <module>
    for item in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

于是我查询了Python的IO操作 ,open()函数的读写模式

w     以写方式打开,
a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
**r+     以读写模式打开**
w+     以读写模式打开 (参见 w )
a+     以读写模式打开 (参见 a )
**rb     以二进制读模式打开**
wb     以二进制写模式打开 (参见 w )
ab     以二进制追加模式打开 (参见 a )
rb+    以二进制读写模式打开 (参见 r+ )
wb+    以二进制读写模式打开 (参见 w+ )
ab+    以二进制读写模式打开 (参见 a+ )*

发现是读写模式的错误,我的csv文件内的内容为是ASCII编码的文本文件,应该用r 模式打开,rb 模式在读取二进制文件,比如图片、视频时使用,于是我将rb 换为r。 然后运行通过。

[1, youth, high, no, fair, no]
[2, youth, high, no, excellent, no]
[3, middle_aged, high, no, fair, yes]
经验分享 程序员 微信小程序 职场和发展