Python3中JSON与TXT文件读写中文乱码的解决方案

纸上星河
纸上星河
发布时间:2026-10-13 | 6人浏览过
原创

本文详解Python3处理JSON及TXT文件时中文乱码的成因与解决。核心在于打开文件时指定encoding='utf-8',并在json.dump中设置ensure_ascii=False,确保中文正常显示而非转为Unicode编码或乱码。

Python3默认采用UTF-8编码格式,但在执行dump写入操作时仍需注意特定参数设置,否则可能导致输出异常。

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兼容的Unicode转义序列写入文件。

{
 "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文件写入中文内容时,同样需要在open函数中指定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(':')

以上即为解决Python3中JSON数据包含中文读写问题的完整方案,供读者参考。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表