Как я могу разобрать несколько файлов с помощью дерева элементов и экспортировать вывод в CSV? - PullRequest
0 голосов
/ 31 октября 2019

Это мои коды, я использую синтаксический анализатор дерева элементов для анализа всего списка файлов, могу получить выходные данные, но могу экспортировать только первый файл в списке.

Мне нужно немногопомогите указать мне правильное направление, я не уверен, где я ошибаюсь с дампом данных из XML-файлов.

    from collections import defaultdict, OrderedDict
    from xml.etree import ElementTree as etree
    import csv
    import os



    def parse_node(root, dict, id):

        tag_dict = OrderedDict()
        for key, value in root.attrib.items():
            if id > 1:  # if there are more than one childs with the 
 same tag
                tag_dict[root.tag + str(id) + ':' + key] = value
            else:
                tag_dict[root.tag + ':' + key] = value
        # Get children of node
        children = root.getchildren()
        # If node has one or more child
        if len(children) >= 1:
            # Loop through all the children
            tag_dict_id = defaultdict(lambda: 0)
            for child in children:
                tag_dict_id[child.tag] += 1  # keep track of the children
                # call to recursion function
                # Parse children
                parse_node(child, tag_dict, tag_dict_id[child.tag])
     # If does not have children and is the 'search_node'
        elif len(children) == 0:
          # Store the text inside the node.
            if id > 1:
                tag_dict[root.tag + str(id) + ':text'] = root.text
            else:
                tag_dict[root.tag + ':text'] = root.text
        # update the current dictionary with the new data
        dict.update(tag_dict)
        return dict

Здесь я вызываю библиотеку CSV, чтобы написатьзаголовки и экспорт данных в файл.

    def writeToCSV(records_lib):
        records_list = []  # contains each of the records
        with open('/Users/Neil/Desktop/output.csv', 'w+') as csvfile:
    header = OrderedDict()  # dictionary with the csv header
            for record in records_lib:
                parsed_record = parse_node(record, OrderedDict(), 1)
                for x in parsed_record.keys():
                    header[x] = x
                records_list.append(parsed_record)
            writer = csv.DictWriter(csvfile, fieldnames=header.keys())
            writer.writerow(header)
            for record in records_list:
                writer.writerow(record)



    Here i am setting the path which would take all the files in the list

    path = "/Users/Neil/Desktop/project/apps/Test/Ram/vault/"
    for filename in os.listdir(path):
  # Only get xml files
        if not filename.endswith('.xml'): continue
        print(filename)
        fullname = os.path.join(path, filename)

        tree = etree.parse(fullname)
        # Parse the files..
        # print(tree)
        # Get the root of the XML tree structure
        root = tree.getroot()
        writeToCSV(root)
...