I am using the Requests module to authorise and then pull csv content from a web API and have it running fine in Python 2.7. I now want to write the same script in Python 3.5 but experiencing some issues:
"iterator should return strings, not bytes (did you open the file in text mode?)"
The requests.get
seems to return bytes and not a string, which seems to be related to the encoding issues seen when moving to Python 3.x. The error is raised on the 3rd from last line: next(reader)
. In Python 2.7 this was not an issue because the csv functions were handled in 'wb'
mode.
This article is very similar, but as I'm not opening a csv file directly, I cant seem to force the response text to be encoded this way: 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])