Python 'ascii' 编解码器无法在位置 9 中编码字符 u'\u2013':序号不在范围内 (128)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19232385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:12:30  来源:igfitidea点击:

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

pythondjangocsvexport

提问by GioBot

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

我正在尝试导入 cvs,但出现此错误

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

Unicode error hint

Unicode 错误提示

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

无法编码/解码的字符串是:) 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.

我尝试过 .encode、unicode() 等,但没有任何效果,我不知道我是否需要库或其他东西,因为我在其他机器上有相同的代码并且工作正常。

 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

采纳答案by OBu

Are you using lib cStringIO? I ran into a similar problem after replacing StringIO with cStringIO. Going back to StringIO was the solution.

你在使用 lib cStringIO 吗?在用 cStringIO 替换 StringIO 后,我遇到了类似的问题。回到 StringIO 是解决方案。

Furthermore, you can try using

此外,您可以尝试使用

from __future__ import unicode_literals

as the first line of your code.

作为代码的第一行。

回答by bcollins

I'm guessing your using python 2.x?

我猜你用的是 python 2.x?

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

如果是这样,请尝试在写入时在字符串上使用 .encode('utf-8') 。