在使用Unicodesv的python中,“str”对象没有属性“decode”

2024-09-25 00:33:10 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码给出了Python3.8中的一个错误,使用networkx,unicodesv

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'

Tags: csv代码innetworkxfordataas错误
3条回答

当您尝试解码已解码的str时,会发生此错误。您是否正确地传递了参数

资料来源:'str' object has no attribute 'decode'. Python 3 error?

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对于Python2更有用,因为标准库的csv模块的unicode处理较差。在Python3中,您可以在打开文件并将结果文件对象传递给标准库的csv模块时指定编码

csv中的reader方法接受一个reader而不是一个str

勾选this post

相关问题 更多 >