Python 如何處理存檔編碼錯誤

有時存檔時遇到編碼錯誤但又不確定資料的編碼

這篇文章教導你如何在不知道資料編碼
但要存檔遇到 UnicodeEncodeError 錯誤時的處理方式

解法

這時候就要利用 Python3 unicode string 的優勢了

也就是說資料一定可以正確地存在 Python3 string 裡
但不一定可以被編碼成你想要的編碼,例如 🙏

這時候只要施一個小魔法處理一下就可以囉

1
2
3
4
5
def write_file(data:str):
data = data.encode("utf-16",'surrogatepass').decode("utf-16","surrogatepass")

with open('qq.json', 'w', encoding='utf-8') as f:
f.write(data)

這段程式碼是先把字串以 utf-16 編碼一次
關鍵是使用 surrogatepass (or ignore 看你需求) 處理之後再解碼回來
最後寫入檔案

如果是在使用 json.dump 時遇到
可以先使用 json.dumps 組合成字串再做處理

1
2
3
4
5
6
7
import json
def write_file(file_path: str, file_data: dict):
file_data = json.dumps(file_data, indent=4, ensure_ascii=False)
file_data = file_data.encode("utf-16",'surrogatepass').decode("utf-16","surrogatepass")

with open(file_path, 'w', encoding='utf-8') as f:
f.write(file_data)

完成 ✅

相關文章