Python _csv.Error:迭代器应该返回字符串,而不是字节(您是否以文本模式打开文件?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22132034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
提问by ap306
At the start of my csv program:
在我的 csv 程序开始时:
import csv # imports the csv module
import sys # imports the sys module
f = open('Address Book.csv', 'rb') # opens the csv file
try:
reader = csv.reader(f) # creates the reader object
for row in reader: # iterates the rows of the file in orders
print (row) # prints each row
finally:
f.close() # closing
And the error is:
错误是:
for row in reader: # iterates the rows of the file in orders
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
采纳答案by Aaron Hall
Instead of this (and the rest):
而不是这个(和其余的):
f = open('Address Book.csv', 'rb')
Do this:
做这个:
with open('Address Book.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
The context manager means you don't need the finally: f.close(), because it will automatically close the file on an error, or on exiting the context.
上下文管理器意味着您不需要finally: f.close(),因为它会在出现错误或退出上下文时自动关闭文件。
回答by Garren S
The solution in this (duplicate?) question csv.Error: iterator should return strings, not byteshelped me:
这个(重复?)问题csv.Error: iterator should return strings, not bytes 中的解决方案帮助了我:
f = open('Address Book.csv', "rt")
or
或者
with open('Address Book.csv', "rt") as f:
or (using gzip)
或(使用 gzip)
import gzip
f = gzip.open('Address Book.csv', "rt")
or
或者
import gzip
gzip.open('Address Book.csv', "rt") as f:

