【发布时间】:2016-11-10 23:27:17
【问题描述】:
我正在使用 Requests 模块进行授权,然后从 Web API 中提取 csv 内容,并让它在 Python 2.7 中运行良好。我现在想在 Python 3.5 中编写相同的脚本,但遇到了一些问题:
"iterator should return strings, not bytes (did you open the file in text mode?)"
requests.get 似乎返回字节而不是字符串,这似乎与迁移到 Python 3.x 时出现的编码问题有关。错误在最后一行的第 3 行引发:next(reader)。在 Python 2.7 中这不是问题,因为 csv 函数是在 'wb' 模式下处理的。
这篇文章非常相似,但由于我没有直接打开 csv 文件,我似乎无法强制以这种方式对响应文本进行编码: csv.Error: iterator should return strings, not bytes
countries = ['UK','US','CA']
datelist = [1,2,3,4]
baseurl = 'https://somewebsite.com/exporttoCSV.php'
#--- For all date/cc combinations
for cc in countries:
for d in datelist:
#---Build API String with variables
url = (baseurl + '?data=chart&output=csv' +
'&dataset=' + d +
'&cc=' + cc)
#---Run API Call and create reader object
r = requests.get(url, auth=(username, password))
text = r.iter_lines()
reader = csv.reader(text,delimiter=',')
#---Write csv output to csv file with territory and date columns
with open(cc + '_'+ d +'.csv','wt', newline='') as file:
a = csv.writer(file)
a.writerow(['position','id','title','kind','peers','territory','date']) #---Write header line
next(reader) #---Skip original headers
for i in reader:
a.writerow(i +[countrydict[cc]] + [datevalue])
【问题讨论】:
-
您是否尝试过将字节转换为 python 字符串?如此处所示? stackoverflow.com/questions/606191/…
-
@Bamcclur 我尝试添加
.decode("utf-8"),但不确定将其放在哪里尝试。我尝试插入它的每个地方,它都说该对象没有属性解码? -
我认为这是因为 iter_lines() 可能是一个列表,您需要解码每个字符串。也许这可以帮助:stackoverflow.com/questions/36971345/…
标签: python-3.x csv python-requests