python将xml文件转换为json

直接上代码:

import os
import json
import xmltodict
 
def xml_to_JSON(xml):
    # 格式转换
    try:
        convertJson = xmltodict.parse(xml, encoding = 'utf-8')
        jsonStr = json.dumps(convertJson, indent=1)
        return jsonStr
    except Exception:
        print('something has occurred')
        pass
 
def find_read_list(path):
    # 获取该文件夹下所有以.xml为后缀的文件
    file_list = os.listdir(path)
    read_list = []
    for i in file_list:
        a, b = os.path.splitext(i)
        if b == '.xml':
            read_list.append(i)
        else:
            continue
    return read_list
 
def batch_convert(path):
    # 主函数
    in_list = find_read_list(path)
    print(in_list)
    for item in in_list:
        with open(path+'\\'+item, encoding = 'utf-8') as f:
            xml = f.read()
            converted_doc = xml_to_JSON(xml)
        new_name = item.rsplit('.xml')[0] + '.json'
        with open(path+'\\'+new_name, 'w+',encoding = 'utf-8') as f:
            f.write(converted_doc)
            print('{} has finished'.format(new_name))
 
# 在这边输入文件夹路径,接下来就会把这个文件夹下所有以.xml为后缀的文件转换为.json文件
# 注意Python文件路径的输入格式 \\
batch_convert('E:\\project\\tmp\\11')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值