1

I'm currently running into an issue when trying to write data into a file from an api get request. the error is the following message: "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 1: ordinal not in range(128)"

I know this means I must convert the text from ascii to utf-8, but I'm not sure how to do this. This is the code that I have so far

import urllib2 import json def moviesearch(query): title = query api_key = "" f = open('movie_ID_name.txt', 'w') for i in range(1,15,1): api_key = "http://api.themoviedb.org/3/search/movie?api_key=b4a53d5c860f2d09852271d1278bec89&query="+title+"&page="+str(i) json_obj = urllib2.urlopen(api_key) json_obj.encode('utf-8') data = json.load(json_obj) for item in data['results']: f.write("<"+str(item['id'])+", "+str(item['title'])+'>\n') f.close() moviesearch("life") 

When I run this I get the following error: AttributeError: addinfourl instance has no attribute 'encode'

What can I do to solve this? Thanks in advance!

1 Answer 1

1

Encoding/decoding only makes sense on things like byte strings or unicode strings. The strings in the data dictionary are Unicode, which is good, since this makes your life easy. Just encode the value as UTF-8:

import urllib2 import json def moviesearch(query): title = query api_key = "" with open('movie_ID_name.txt', 'w') as f: for i in range(1,15,1): api_key = "http://api.themoviedb.org/3/search/movie?api_key=b4a53d5c860f2d09852271d1278bec89&query="+title+"&page="+str(i) json_obj = urllib2.urlopen(api_key) data = json.load(json_obj) for item in data['results']: f.write("<"+str(item['id'])+", "+item['title'].encode('utf-8')+'>\n') moviesearch("life") 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.