3 回答

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

TA贡献1853条经验 获得超6个赞
我只是用我的代码解决了这个问题。引发该异常的原因是因为您有参数rb。将其更改为r。
您的代码:
import csv
ifile = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
print (row)
新代码:
import csv
ifile = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
print (row)

TA贡献1794条经验 获得超7个赞
您的问题是您b的open标志中有。标志rt(读取,文本)是默认设置,因此,使用上下文管理器只需执行以下操作:
with open('sample.csv') as ifile:
read = csv.reader(ifile)
for row in read:
print (row)
上下文管理器意味着您不需要常规的错误处理(如果没有这种处理,您可能会卡在打开文件中,尤其是在解释器中),因为它会在发生错误或退出上下文时自动关闭文件。
上面的与:
with open('sample.csv', 'r') as ifile:
...
要么
with open('sample.csv', 'rt') as ifile:
...
添加回答
举报