|
| 1 | +""" |
| 2 | +data_export module |
| 3 | +This module provides functions to export data to various file formats. |
| 4 | +""" |
| 5 | +import json |
| 6 | +import csv |
| 7 | +import xml.etree.ElementTree as ET |
| 8 | +from typing import List, Dict, Any |
| 9 | + |
| 10 | +def export_to_json(data: List[Dict[str, Any]], filename: str) -> None: |
| 11 | + """ |
| 12 | + Export data to a JSON file. |
| 13 | + |
| 14 | + :param data: List of dictionaries containing the data to export |
| 15 | + :param filename: Name of the file to save the JSON data |
| 16 | + """ |
| 17 | + with open(filename, 'w', encoding='utf-8') as f: |
| 18 | + json.dump(data, f, ensure_ascii=False, indent=4) |
| 19 | + print(f"Data exported to {filename}") |
| 20 | + |
| 21 | +def export_to_csv(data: List[Dict[str, Any]], filename: str) -> None: |
| 22 | + """ |
| 23 | + Export data to a CSV file. |
| 24 | + |
| 25 | + :param data: List of dictionaries containing the data to export |
| 26 | + :param filename: Name of the file to save the CSV data |
| 27 | + """ |
| 28 | + if not data: |
| 29 | + print("No data to export") |
| 30 | + return |
| 31 | + |
| 32 | + keys = data[0].keys() |
| 33 | + with open(filename, 'w', newline='', encoding='utf-8') as f: |
| 34 | + writer = csv.DictWriter(f, fieldnames=keys) |
| 35 | + writer.writeheader() |
| 36 | + writer.writerows(data) |
| 37 | + print(f"Data exported to {filename}") |
| 38 | + |
| 39 | +def export_to_xml(data: List[Dict[str, Any]], filename: str, root_element: str = "data") -> None: |
| 40 | + """ |
| 41 | + Export data to an XML file. |
| 42 | + |
| 43 | + :param data: List of dictionaries containing the data to export |
| 44 | + :param filename: Name of the file to save the XML data |
| 45 | + :param root_element: Name of the root element in the XML structure |
| 46 | + """ |
| 47 | + root = ET.Element(root_element) |
| 48 | + for item in data: |
| 49 | + element = ET.SubElement(root, "item") |
| 50 | + for key, value in item.items(): |
| 51 | + sub_element = ET.SubElement(element, key) |
| 52 | + sub_element.text = str(value) |
| 53 | + |
| 54 | + tree = ET.ElementTree(root) |
| 55 | + tree.write(filename, encoding='utf-8', xml_declaration=True) |
| 56 | + print(f"Data exported to {filename}") |
| 57 | + |
0 commit comments