使用Python将希伯来语写入文本文件时出现编码问题


Django项目

编码问题:代码的流程

  1. 读取Excel文件

  2. 操作Excel 中的数据

  3. 创建新的txt文件并写入

  4. 将txt文件发送到客户端

    coding = "utf8"
    file = open(filename, "w", encoding=coding, errors="ignore") 
    for row in excel_data_df.iloc():
    line = manipulate(row)
    file.write(line)
    file.close()
    file_data = open(filename, "r", encoding=coding, errors="ignore")
    response = HttpResponse(file_data, content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=' + filename 
    

一切都很好,但当我用ANSI编码打开文件时,所有希伯来语都变成了胡言乱语的

我试着用每一个希伯来语选项更改编码https://docs.python.org/2.4/lib/standard-encodings.html

希伯来语编码应使用ASCII NEW CODE或ASCII WINDOWS TEXT编写,有什么想法吗?

您需要将模式更改为"rb";并删除编码参数

file = open(filename, "w") 
for row in excel_data_df.iloc():
line = manipulate(row)
file.write(line)
file.close()
file_data = open(filename, "rb")
response = HttpResponse(file_data, content_type='application/vnd.ms- 
excel')
response['Content-Disposition'] = 'attachment; filename=' + filename 

最新更新