csv.Error:迭代器应返回字符串,而不是字节 [英] csv.Error: iterator should return strings, not bytes

查看:93
本文介绍了csv.Error:迭代器应返回字符串,而不是字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Sample.csv包含以下内容:

Sample.csv contains the following:

NAME    Id   No  Dept
Tom     1    12   CS
Hendry  2    35   EC
Bahamas 3    21   IT
Frank   4    61   EE

Python文件包含以下代码:

And the Python file contains the following code:

import csv
ifile  = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
    print (row) 

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

When I run the above code in Python, I get the following exception:

文件"csvformat.py",第4行,在 对于读入的行: _csv.Error:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)

File "csvformat.py", line 4, in for row in read : _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

我该如何解决?

推荐答案

您以文本模式打开文件.

You open the file in text mode.

更具体地说:

ifile  = open('sample.csv', "rt", encoding=<theencodingofthefile>)

编码的很好的猜测是"ascii"和"utf8".您也可以关闭编码,它将使用系统默认编码,该编码通常为UTF8,但可能还有其他含义.

Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.

这篇关于csv.Error:迭代器应返回字符串,而不是字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆