Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 附加到文本文件时,非英语字符会损坏_Python 3.x_File_Write_Non English - Fatal编程技术网

Python 3.x 附加到文本文件时,非英语字符会损坏

Python 3.x 附加到文本文件时,非英语字符会损坏,python-3.x,file,write,non-english,Python 3.x,File,Write,Non English,我试图在js文件中添加一些文本,其中包含非英语字符,如“ç,ş,ı” 追加文本是dinamic,当它包含非英语字符时,js文件中的非英语字符会损坏 string = '{ "type": "Feature", "properties": { "color": "' + colors[color] + '", "geometry": "Point", &quo

我试图在js文件中添加一些文本,其中包含非英语字符,如“ç,ş,ı”

追加文本是dinamic,当它包含非英语字符时,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()

如果您尝试使用unicode字符串写入文件,那么当您将unicode字符串写入文件时,python会尝试使用ASCII编码。这就是文本被破坏的原因。要修复此问题,请将文本编码为
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()