欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用python实现字典格式的文件利用key取value并写入txt或者csv文件

程序员文章站 2022-07-08 09:40:38
...
# coding=gbk
#--------------------------------利用key取value-----------------------------------------------
import json
items=  {"totalPages":33,"numberOfElements":20,"totalElements":647,"content":[{"id":1,"schoolName":"北京大学","schoolCode":"10001","schoolIdentificationCode":"4111010001","department":"教育部","provinces":"北京","city":"北京市","educationLevel":"本科","isPrivateSchool":"","isDoubleTop":"双一流","isNineEightFive":"985","isTwoOneOne":"211","isOneZeroZero":"","wslCountry":"2","wslProvinces":"2","xyhCountry":"1","xyhCrovinces":"1","schoolUrl":"http://www.gotopku.cn/"},{"id":2,"schoolName":"中国人民大学","schoolCode":"10002","schoolIdentificationCode":"4111010002","department":"教育部","provinces":"北京","city":"北京市","educationLevel":"本科","isPrivateSchool":"","isDoubleTop":"双一流","isNineEightFive":"985","isTwoOneOne":"211","isOneZeroZero":"","wslCountry":"21","wslProvinces":"3","xyhCountry":"8","xyhCrovinces":"3","schoolUrl":"http://rdzs.ruc.edu.cn/"},{"id":18,"schoolName":"中国农业大学","schoolCode":"10019","schoolIdentificationCode":"4111010019","department":"教育部","provinces":"北京","city":"北京市","educationLevel":"本科","isPrivateSchool":"","isDoubleTop":"双一流","isNineEightFive":"985","isTwoOneOne":"211","isOneZeroZero":"","wslCountry":"35","wslProvinces":"7","xyhCountry":"33","xyhCrovinces":"6","schoolUrl":"http://jwzs.cau.edu.cn/"}],"number":1}
# print(type(items))
item=json.dumps(items) # 转为json格式
jsons=json.loads(item) # json格式解析
# print(jsons)
ss=jsons['content']
# print(ss)
for s in ss: #字典遍历取值
    # print(s['schoolName'])

    #  没有指定任何文件格式,也能写入成功,然后可以右击文件,选择打开文件的方式
    with open ('our_school',"a+",encoding="utf-8") as f:
        f.write(s['schoolName']+'\r\n')
    #  写入txt文件

    with open ('our_school.txt',"a+",encoding="utf-8") as f:
        f.write(s['schoolName']+'\r\n')
    #  写入csv文件
    with open ('our_school.csv',"a+",newline='',encoding="utf-8-sig") as f: # 注意此处写encoding="utf-8"会出现乱码;此外,使用newline=''避免出现空行
        f.write(s['schoolName']+'\r\n')

# 最终结果--------------------------------------------------------------------

使用python实现字典格式的文件利用key取value并写入txt或者csv文件

 

使用python实现字典格式的文件利用key取value并写入txt或者csv文件

 

注意:当字典比较乱时,可以百度搜索“在线代码格式化”

使用python实现字典格式的文件利用key取value并写入txt或者csv文件