简体   繁体   中英

Encoding issue when writing Hebrew to text file, with Python

Django Project

Encoding problem: The flow of code

  1. reading Excel file

  2. manipulate the data from the Excel

  3. create new txt file and write into it

  4. send the txt file to the client

    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

every thing is working just fine but when I open the the file with ANSI Encoding all the Hebrew change into gibberish

I have try to change the coding with every Hebrew option https://docs.python.org/2.4/lib/standard-encodings.html

The Hebrew coding should be write with ASCII NEW CODE or ASCII WINDOWS TEXT, any ideas?

You need to change the mode to "rb" and remove the encoding parameter

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM