python - 'str'对象在带有unicodecsv的python中没有属性'decode'
问题描述
下面的代码在 python 3.8 中给出了一个错误,带有 networkx,unicodecsv
with open('hero-network.csv', 'r') as data:
reader = csv.reader(data)
**for row in reader:**
graph.add_edge(*row)
AttributeError: 'str' object has no attribute 'decode'
解决方案
unicodescv.reader
期望以二进制模式打开文件,因为至少在理论上,它将解决如何解码字节。
with open('hero-network.csv', 'rb') as data: # the mode is 'rb', not 'r'
reader = csv.reader(data)
for row in reader:
graph.add_edge(*row)
正如评论中所指出的unicodecsv
,当标准库的 csv 模块的 unicode 处理很差时,它对 Python2 更有用。在 Python 3 中,您可以在打开文件并将生成的文件对象传递给标准库的 csv 模块时指定编码。
推荐阅读
- html - 应用的 CSS 导致锚点无法点击
- vue.js - Vue:事件总线处理程序未定义
- javascript - 嵌套折线图未显示
- oauth-2.0 - 在 OpenID 流中提交令牌请求时如何修复“无效签名”API 错误?
- c# - 如何将结构数组从 c++ 传递到 c#?
- javascript - React hooks - setState 没有更新状态属性以显示侧边栏
- javascript - 我不知道为什么我不断收到此错误
- c++ - 我可以从样式表 (qss) 更改自定义动态属性吗?
- android - 我在哪里可以找到用于对象地标检测的 Tensorflow lite 项目(例如面部地标)?
- binary - 求十进制整数 -102 的 8 位 2 的补码