Skip to content Skip to sidebar Skip to footer

Parse Many Xml Files To One Csv File

The code below takes an XML file and parses specific elements into a CSV file. Regarding the code I had simpler and different code that had a slightly different out, the code below

Solution 1:

Try:

from pathlib import Path

directory = 'C:/Users/docs/FolderwithXMLs'withopen('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)

    headers = ['id', 'service_code', 'rational', 'qualify', 'description_num', 'description_txt', 'set_data_xin', 'set_data_xax', 'set_data_value', 'set_data_x']

    writer.writerow(headers)

    xml_files_list = list(map(str,Path(directory).glob('**/*.xml')))
    for xml_file in xml_files_list:
        tree = ET.parse(xml_file)
        root = tree.getroot()

        start_nodes = root.findall('.//START')
        for sn in start_nodes:
            row = defaultdict(str)

            # <<<<< Indentation was wrong herefor k,v in sn.attrib.items():
                row[k] = v

            # Rest of the code here.

Hope that helps.

Post a Comment for "Parse Many Xml Files To One Csv File"