Skip to content

Commit f9c1432

Browse files
authored
Merge pull request #767 from ScrapeGraphAI/fix-export-function
2 parents fd57cc7 + 6179ab9 commit f9c1432

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

scrapegraphai/utils/data_export.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
 (0)