python读取json文件并转成csv或excel文件

执行前需安装依赖包

pip install pandas openpyxl

python 代码

#!/usr/bin/python3
import json
import collections
import glob
import pandas
from dataclasses import make_dataclass

#读取json文件列表path(windows系统)
jsonfiles = glob.glob('C:\\Users\\os-hui.guo\\Desktop\\py\\systeminfo*.json')
#读取json文件列表path(linux系统)
#jsonfiles = glob.glob('/usr/local/systeminfo*.json')
#输出文件path
outCsvPath = "out.csv"
outXlsxPath = "out.xlsx"
#输出文件表头
Model = make_dataclass("Model", [("model", str), ("count", int), ("model2", str), ("count2", int), ("model3", str), ("count3", int)])

modelList = []
#输出处理文件列表
print(jsonfiles)
for file in jsonfiles:
    sysFile = open(file,"r")
    sysJson = json.load(sysFile)
    allList = sysJson['system_info']['System']
    modalList = []
    for aitem in allList:
        modalList.append(aitem['Model'])
    countList = collections.Counter(modalList).items()
    model = Model('','','','','','')
    for citem in countList:
        if model.model == '':
            model.model = citem[0]
            model.count = citem[1]
        elif model.model2 == '':
            model.model2 = citem[0]
            model.count2 = citem[1]
    sysFile.close()
    modelList.append(model)

data = pandas.DataFrame(modelList)
#生成csv文件
data.to_csv(outCsvPath,header=True,index=False,sep=",")
#生成xlsx文件
data.to_excel(outXlsxPath,header=True,index=False)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值