新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:解決python3json數(shù)據(jù)包含中文的讀寫問題
python3 默認的是UTF-8格式,但在在用dump寫入的時候仍然要注意:如下

創(chuàng)新互聯(lián)建站網(wǎng)絡公司擁有十載的成都網(wǎng)站開發(fā)建設經(jīng)驗,上千余家客戶的共同信賴。提供成都網(wǎng)站建設、網(wǎng)站制作、網(wǎng)站開發(fā)、網(wǎng)站定制、友情鏈接、建網(wǎng)站、網(wǎng)站搭建、成都響應式網(wǎng)站建設公司、網(wǎng)頁設計師打造企業(yè)風格,提供周到的售前咨詢和貼心的售后服務
import JSON
data1 = {
"TestId": "testcase001",
"Method": "post",
"Title": "登錄測試",
"Desc": "登錄基準測試",
"Url": "http://xxx.xxx.xxx.xx",
"InputArg": {
"username": "王小丫",
"passwd": "123456",
},
"Result": {
"errorno": "0"
}
}
with open('casedate.json', 'w', encoding='utf-8') as f:
json.dump(data1, f, sort_keys=True, indent=4)在打開文件的時候要加上encoding=‘utf-8',不然會顯示成亂碼,如下:
{
"Desc": "??????????",
"InputArg": {
"passwd": "123456",
"username": "??С?"
},
"Method": "post",
"Result": {
"errorno": "0"
},
"TestId": "testcase001",
"Title": "???????",
"Url": "http://xxx.xxx.xxx.xx"
}在dump的時候也加上ensure_ascii=False,不然會變成ascii碼寫到文件中,如下:
{
"Desc": "\u767b\u5f55\u57fa\u51c6\u6d4b\u8bd5",
"InputArg": {
"passwd": "123456",
"username": "\u738b\u5c0f\u4e2b"
},
"Method": "post",
"Result": {
"errorno": "0"
},
"TestId": "testcase001",
"Title": "\u767b\u5f55\u6d4b\u8bd5",
"Url": "http://xxx.xxx.xxx.xx"
}另外python3在向txt文件寫中文的時候也要注意在打開的時候加上encoding=‘utf-8',不然也是亂碼,如下:
with open('result.txt', 'a+', encoding='utf-8') as rst:
rst.write('return data')
rst.write('|')
for x in r.items():
rst.write(x[0])
rst.write(':') 網(wǎng)站題目:創(chuàng)新互聯(lián)Python教程:解決python3json數(shù)據(jù)包含中文的讀寫問題
文章起源:http://m.fisionsoft.com.cn/article/dpsdphg.html


咨詢
建站咨詢
