Python: UnicodeEncodeError: ascii codec cannot encode character u '\ xf1' at position 78: ordinal not in range (128)

I have tried two solutions for this problem, but will result in a different error. Try it first encode

and the other tries strip

(#) to suggest that the problem was caught in this error:

"color":rcolor,"text_color":tcolor})
File "/usr/lib/python2.7/csv.py", line 152, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 78: ordinal not in range(128)

      

My code now looks like this:

routes = db.routes.find()
    for route in routes:
        try:
            color = route["properties"]["color"]
            color = color.strip('#')
            print(color)

            tcolor = route["properties"]["tcolor"]
            tcolor = tcolor.strip('#')
            print(tcolor)
        except KeyError:
            color = "0000FF"
            tcolor = ""

        writer.writerow({"route_id":route["route_id"],
                   "agency_id":route["properties"]["agency_id"],...,
                   "route_color":color,"route_text_color":tcolor})

      

I'm not really sure why it keeps getting unicode error ...

+3


source to share


1 answer


Try to parse your dict to have unicode values ​​before writing to csv.

def convert(input):
    if isinstance(input, dict):
        return {convert(key): convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

if __name__ == "__main__":
    utf_route = convert(route)

      



So if you get an error while writing to csv try one of them below

import codecs

with codecs.open("local/file1.csv", "w", encoding='utf8') as f:
    writer = csv.writer(f, delimiter=",")
    writer.writerow(data.keys())
    writer.writerow(data.values())

      

+1


source







All Articles