json与csv格式相互转换

json库

csv转json格式代码

#e14.1csv2json.py
import json
fr=open("Python2.csv","r",encoding='utf-8')
ls=[]
for line in fr:
    line=line.replace("\n","")
    ls.append(line.split(','))
fr.close()
fw=open("Python2.json","w",encoding='utf-8')
for i in range(1,len(ls)):
    ls[i]=dict(zip(ls[0],ls[i]))
json.dump(ls[1:],fw,sort_keys=True,indent=4,ensure_ascii=False)
fw.close()

结果显示

json转csv格式代码

#14.2json2csv.py
import json
fr=open("python2.json","r",encoding="utf-8")
ls=json.load(fr)
data=[ list(ls[0].keys()) ]
for item in ls:
    data.append(list(item.values()))
fr.close()
fw=open("python4.csv","w",encoding="utf-8")
for item in data:
    fw.write(",".join(item)+"\n")
fw.close()

结果显示

 

posted @ 2019-05-06 13:36  .SG  阅读(4734)  评论(0编辑  收藏  举报