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

查看:21
本文介绍了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天全站免登陆