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:\Users\ThinkCentre\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)
  File "D:\Users\ThinkCentre\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.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']
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值