【问题标题】:While appending to text file, non-english characters get corrupted附加到文本文件时,非英文字符会损坏
【发布时间】:2021-07-28 17:09:44
【问题描述】:

我正在尝试将一些文本附加到 js 文件中,它包含非英语字符,例如 'ç,ş,ı'。

附加文本是动态的,当它包含非英文字符时,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()

【问题讨论】:

    标签: python-3.x file write non-english


    【解决方案1】:

    如果您尝试使用 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多