python写utf8文件

来源:互联网 发布:知无涯者书 编辑:程序博客网 时间:2024/05/29 05:02

【1】使用默认open方式,

需要自己确保需要的编码方式,如下例子中xxx.json为utf8格式,读入后为unicode,需要转为utf8再写文件

name='xxx.json'f=open(name,'r')of=open(name+'.txt','w')for line in f:dictdata=json.loads(line)out=json.dumps(dictdata,indent=4<span style="color:#3333ff;">, ensure_ascii=False</span>).encode('utf8')of.write(out+'\n')of.close()
对于如上json格式化的例子来说,ensure_ascii也是可以不要的。

【2】使用codecs库

这时候需要指定的是读入或写出的文件的编码。

name='xxx.json'f=codecs.open(name,'r',encoding='utf8')of=codecs.open(name+'.txt','w', encoding='utf8')for line in f:dictdata=json.loads(line)out=json.dumps(dictdata,indent=4, ensure_ascii=False)of.write(out+'\n')of.close()
这种方式ensure_ascii貌似一定需要的了。

0 0
原创粉丝点击