【发布时间】:2018-03-28 11:05:42
【问题描述】:
我正在编写一个脚本,该脚本使用 tje 请求库从 URL 获取 zip 文件。该 zip 文件包含一个 csv 文件。我正在尝试读取该 csv 文件而不保存它。但是在解析时它给了我这个错误:_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
import csv
import requests
from io import BytesIO, StringIO
from zipfile import ZipFile
response = requests.get(url)
zip_file = ZipFile(BytesIO(response.content))
files = zip_file.namelist()
with zip_file.open(files[0]) as csvfile:
csvreader = csv.reader(csvfile)
# _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
for row in csvreader:
print(row)
【问题讨论】:
-
ZipFile.open返回二进制流,但csv.reader需要文本流。您必须添加一个将二进制数据解码为文本的包装器。