csv.Error:迭代器应返回字符串,而不是字节

Sample.csv包含以下内容:


NAME    Id   No  Dept

Tom     1    12   CS

Hendry  2    35   EC

Bahamas 3    21   IT

Frank   4    61   EE

Python文件包含以下代码:


import csv

ifile  = open('sample.csv', "rb")

read = csv.reader(ifile)

for row in read :

    print (row) 

当我在Python中运行上述代码时,出现以下异常:


文件“ csvformat.py”,第4行,在已读行中为_:_ csv.Error:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)


我该如何解决?


精慕HU
浏览 536回答 3
3回答

HUH函数

您以文本模式打开文件。进一步来说:ifile&nbsp; = open('sample.csv', "rt", encoding=<theencodingofthefile>)编码的不错猜测是“ ascii”和“ utf8”。您还可以关闭编码,它将使用系统默认编码,该编码通常为UTF8,但可能还有其他含义。

墨色风雨

我只是用我的代码解决了这个问题。引发该异常的原因是因为您有参数rb。将其更改为r。您的代码:import csvifile&nbsp; = open('sample.csv', "rb")read = csv.reader(ifile)for row in read :&nbsp; &nbsp; print (row)&nbsp;新代码:import csvifile&nbsp; = open('sample.csv', "r")read = csv.reader(ifile)for row in read :&nbsp; &nbsp; print (row)

慕田峪9158850

您的问题是您b的open标志中有。标志rt(读取,文本)是默认设置,因此,使用上下文管理器只需执行以下操作:with open('sample.csv') as ifile:&nbsp; &nbsp; read = csv.reader(ifile)&nbsp;&nbsp; &nbsp; for row in read:&nbsp; &nbsp; &nbsp; &nbsp; print (row)&nbsp;&nbsp;上下文管理器意味着您不需要常规的错误处理(如果没有这种处理,您可能会卡在打开文件中,尤其是在解释器中),因为它会在发生错误或退出上下文时自动关闭文件。上面的与:with open('sample.csv', 'r') as ifile:&nbsp; &nbsp; ...要么with open('sample.csv', 'rt') as ifile:&nbsp; &nbsp; ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python