_csv.Error:迭代器应返回字符串,而非字节(您是否以文本模式打开文件?)
在我这个处理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
然后出现的错误是:
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?)
2 个回答
2
这个(重复的?)问题中的解决方案 csv.Error: 迭代器应该返回字符串,而不是字节 对我有帮助:
f = open('Address Book.csv', "rt")
或者
with open('Address Book.csv', "rt") as f:
或者(使用gzip)
import gzip
f = gzip.open('Address Book.csv', "rt")
或者
import gzip
gzip.open('Address Book.csv', "rt") as f:
15
与其这样做(以及后面的内容):
f = open('Address Book.csv', 'rb')
不如这样做:
with open('Address Book.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
上下文管理器的意思是,你不需要写 finally: f.close()
这行代码,因为它会在出错时或者退出上下文时自动关闭文件。