首页 > 解决方案 > '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'

标签: python

解决方案


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 模块时指定编码。


推荐阅读