json寫入中文字符並顯示
想把一個字典{"name":"張三"}形式的數據寫入文本中,並且能顯示中文字符
dict = {'name':'張三'}
with open('a.txt','w',encoding='utf-8') as f:
f.write(dict)
在python中如果這樣直接寫的話,會出現TypeError異常:寫入的數據必須是字符串,不能是字典。
所以得將它轉換成字符串的形式,用json格式來寫入。但是在寫入的文本中不能顯示想看的中文字符{"name": "\u5f20\u4e09"}
,在json中加一個ensure_ascii=False參數就能解決啦
import json
dict = {'name':'張三'}
with open('a.txt','w',encoding='utf-8') as f:
f.write(json.dumps(dict,ensure_ascii=False))