Skip to main content
 首页 » 编程设计

python之如何在python 2.7.8中将dict写入非英文字符的文件

2024年10月25日10zhoujg

这是一个简单的例子:

test = {'location': '北京', 'country': '中国'}  # the values are Chinese.   

在文件 test.log 中:

{'location': '北京', 'country': '中国'}  

在python 2.7.8中,当我需要输出数据时,我使用str()方法。

file_out = open('test.log', 'w') 
file_out.write(str(test)) 
file_out.close() 

str() 方法在 dict 包含其他字符时不起作用。我知道在python2中默认是ASCII,这个不支持中文。

我的问题是如何将字典输出到文件中?有人给我提过Json包,但是我不知道怎么用。

请您参考如下方法:

这就是你想要的。

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
 
import json 
ori_test = {'location': '北京', 'country': '中国'} 
test = dict([(unicode(k, "utf-8"), unicode(v, "utf-8")) for k, v in ori_test.items()]) 
 
my_dict = json.dumps(test, ensure_ascii=False).encode('utf8') 
print my_dict 
# then write my_dict to the local file as you want 

还有这个link可能对您有所帮助。