python:json.dump输出为utf-8编码的文件
将 dict 转为 str,在解码编码通过 write 形式写入
with open(sscapRootPath,'w',encoding="utf-8") as f:
ssr_list=json.dumps(ssr_list,indent=4,separators=(',',': '))
f.write(ssr_list.encode('utf-8').decode('unicode_escape'))
代码文件:
import json
test_path=r'D:\K\Program Files\ssr_for_win\gui-config.json'
sscapRootPath=r'D:\K\Program Files\SsCAP\SSCap-v4.0\config'
def getTest():
with open(test_path,'rb') as f:
test_list=json.load(f)
test_list_t=[]
test_dict={} #不能直接使用 dict , 因为是地址传递
print(len(test_list["configs"]))
for i in range(len(test_list["configs"])):
s_server=test_list["configs"][i]["server"]
s_server_port=test_list["configs"][i]["server_port"]
s_password=test_list["configs"][i]["password"]
s_method=test_list["configs"][i]["method"]
s_remarks=test_list["configs"][i]["remarks"]
s_group=test_list["configs"][i]["group"]
s_enable= True
test_list_t.append({"server":s_server,"server_port":s_server_port,
"password":s_password,"method":s_method,"remarks":s_remarks,"group":s_group})
# gui-config-bk.json
with open(sscapRootPath+r'\gui-config-bk.json','r',encoding="utf-8") as f:
test_list=json.load(f)
test_list['configs']=test_list_t
with open(sscapRootPath+r'\gui-config.json','w',encoding="utf-8") as f:
test_list=json.dumps(test_list,indent=4,separators=(',',': '))
f.write(test_list.encode('utf-8').decode('unicode_escape'))
#json.dump(test_list,f,indent=4,separators=(',',': '))
if __name__ == '__main__':
getTest()

浙公网安备 33010602011771号