builderPath = sys.path[0]
filePath = builderPath + "/网络库.json"
with open(filePath,mode="r+") as f:
moduleInfo = json.load(f)
print(moduleInfo)
moduleInfo["name"] = u"网络库"
print(moduleInfo["name"])
moduleInfoStr = json.dumps(moduleInfo)
print(moduleInfoStr)
#覆盖写入
f.seek(0)
f.truncate()
f.write(moduleInfoStr)
一个内容为中文的纯文本文件,我用以上代码读入到内存中,修改修改里面的内容,然后重新写回文件,发现文件里面的中文全部无法正常显示了
{"name": "\u7f51\u7edc\u5e93", "frameworks": [], "url": "http://recept.zjzwfw.gov.cn/oss/upload/7a2fb6d4-bef2-4f20-8e38-09fbe0ad157f.zip", "packageName": "zwfw.alibaba.zwnetwork", "bizType": 100, "version": "1.0.1", "relateModuleType": [], "description": "iOS\u7aef\u7f51\u7edc\u5e93"}
原因在于这行方法 json.dumps(moduleInfo),对象转字符串的时候,默认会使用ASCII码进行编码,需要手动设置成非ASCII,
moduleInfoStr = json.dumps(moduleInfo,ensure_ascii=False)
文件读取的地方也要作修改
with open(filePath,mode="r+") as f:
需要修改为io包里提供的open方法
with open(filePath,mode="r+") as f:
原因是io.open()读取出来的是Unicode类型,编码类型是正常的
修改后正确的方法是这样的
builderPath = sys.path[0]
filePath = builderPath + "/网络库.json"
with io.open(filePath,mode="r+") as f:
moduleInfo = json.load(f)
print(moduleInfo)
moduleInfo["name"] = u"网络库"
print(moduleInfo["name"])
moduleInfoStr = json.dumps(moduleInfo,ensure_ascii=False)
print(moduleInfoStr)
#覆盖写入
f.seek(0)
f.truncate()
f.write(moduleInfoStr)