简体   繁体   English

附加到文本文件时,非英文字符会损坏

[英]While appending to text file, non-english characters get corrupted

I am trying to append some text to a js file, and it contains non-english characters like 'ç,ş,ı'.我正在尝试将 append 一些文本添加到 js 文件中,它包含非英语字符,如“ç,ş,ı”。

Appending text is dinamic, when it contains a non-english character, the non-english characters in the js file corrupts.附加文本是动态的,当它包含非英文字符时,js 文件中的非英文字符会损坏。

string = '{ "type": "Feature", "properties": { "color": "' + colors[color] + '", "geometry": "Point", "name": " ' + user_input + '", "description": "' + desc + '" }, "geometry": { "type": "Point", "coordinates": [ ' + str(lng) + ', ' + str(lat) + ' ] } },]};'

f = open('mapdata.js', 'a')
f.write(string)
f.close()

If you try to write to a file with unicode strings, When you write a unicode string to a file, python tries to encode it in ASCII.如果您尝试使用 unicode 字符串写入文件,当您将 unicode 字符串写入文件时,python 会尝试将其编码为 ASCII。 That's why the the text is corrupted.这就是文本被破坏的原因。 To fix that encode the text to utf-8 and open the file as binary.修复将文本编码为utf-8并将文件作为二进制文件打开。

string = '{ "type": "Feature", "properties": { "color": "' + colors[color] + '", "geometry": "Point", "name": " ' + user_input + '", "description": "' + desc + '" }, "geometry": { "type": "Point", "coordinates": [ ' + str(lng) + ', ' + str(lat) + ' ] } },]};'

f = open('mapdata.js', 'ab')
string.encode('utf-8')
f.write(string)
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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