小编Ste*_*eve的帖子

未在Python 3中显式打开文件时处理从字节到字符串的转换

我正在使用Requests模块进行授权,然后从Web API中提取csv内容,并使其在Python 2.7中正常运行。我现在想在Python 3.5中编写相同的脚本,但是遇到一些问题:

"iterator should return strings, not bytes (did you open the file in text mode?)"
Run Code Online (Sandbox Code Playgroud)

requests.get移动到Python 3.x的时候似乎返回字节,而不是一个字符串,它似乎与看到的编码问题 错误从第三行的第三行引发next(reader)。在Python 2.7中,这不是问题,因为csv函数是在'wb'模式下处理的。

本文非常相似,但是由于我没有直接打开csv文件,因此我似乎无法强制以这种方式编码响应文本: csv.Error:迭代器应返回字符串,而不是字节

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, …
Run Code Online (Sandbox Code Playgroud)

csv python-3.x python-requests

5
推荐指数
1
解决办法
7669
查看次数

标签 统计

csv ×1

python-3.x ×1

python-requests ×1