Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'ascii' codec can't encode character u'\u2013' in position 9: ordinal not in range(128)

I'm trying to import to cvs, but I get this error

UnicodeEncodeError at /brokers/csv/'ascii' codec can't encode character u'\u2013' in position 9: ordinal not in range(128)

Unicode error hint

The string that could not be encoded/decoded was: ) 758–9800

I have tried .encode, unicode(), etc and nothing works, I don't know if I need a library or something else, 'cause I have the same code in other machine and is working fine.

 def exportar_a_csv_brokers(request):
     #Fecha actual
     hoy = datetime.now().date()
     #Creado el:
     creado_hoy = hoy.strftime("%m/%d/%Y")
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment;filename=
     "Reporte de Brokers ' +  creado_hoy + '.csv"'
     response['Content-Type'] = 'text/csv; charset=utf-8'
     response.write("\xEF\xBB\xBF")

     writer = csv.writer(response)
     brokers = Broker.objects.all()
     writer.writerow(['Creado el:             ' + creado_hoy + ' '])
     writer.writerow([''])
     writer.writerow(
    ['Apellido Paterno', 'Nombre', '# Broker', '# Licencia de Seguro', 'ID Federal',  'Nombre Agencia', 'Teléfono',
     'Correo Electrónico', 'Fax', 'Calle', '# Interior', 'Colonia', 'Código Postal', 'Estado', 'Ciudad'])

for broker in brokers:
    #Imprimiendo resultados
    writer.writerow([broker.ap_paterno, broker.nombre, broker.no_broker,
                     broker.no_licencia_seguro, broker.id_federal, broker.nombre_agencia, broker.telefono,
                     broker.correo_electronico, broker.fax,
                     broker.calle, broker.no_interior, broker.colonia, broker.codigo_postal, broker.estado,
                     broker.ciudad])
return response
like image 706
GioBot Avatar asked Oct 07 '13 18:10

GioBot


People also ask

What is u2013 character?

Unicode Character “–” (U+2013) – Name: En Dash. Unicode Version: 1.1 (June 1993)

How do I fix UnicodeEncodeError in Python?

Only a limited number of Unicode characters are mapped to strings. Thus, any character that is not-represented / mapped will cause the encoding to fail and raise UnicodeEncodeError. To avoid this error use the encode( utf-8 ) and decode( utf-8 ) functions accordingly in your code.

What character is xe9?

u'\xe9' is a Unicode string that contains the unicode character U+00E9 (LATIN SMALL LETTER E WITH ACUTE).


1 Answers

I'm guessing your using python 2.x?

if so try using .encode('utf-8') on your string when writing.

like image 164
bcollins Avatar answered Sep 24 '22 22:09

bcollins