|
1 | 1 | import json
|
2 | 2 | from datetime import datetime
|
3 | 3 | from pathlib import Path
|
4 |
| -import xml.etree.ElementTree as ET |
| 4 | +import xml.etree.ElementTree as tree |
| 5 | +from typing import Optional |
5 | 6 |
|
6 | 7 |
|
7 |
| -def main() -> None: |
8 |
| - data = { |
9 |
| - "nombre": "Iñaki Silanes", |
10 |
| - "edad": 46, |
11 |
| - "fecha_de_nacimiento": datetime(1977, 6, 11, 9, 0).isoformat(), |
12 |
| - "lenguajes_de_programación": ["python", "bash", "perl", "fortran", "javascript"], |
13 |
| - } |
| 8 | +def main(data: dict) -> None: |
| 9 | + json_file = Path("data.json") |
| 10 | + run_json(data, json_file) |
14 | 11 |
|
15 |
| - run_json(data) |
16 |
| - run_xml(data) |
| 12 | + xml_file = Path("data.xml") |
| 13 | + run_xml(data, xml_file) |
17 | 14 |
|
18 | 15 |
|
19 |
| -def run_json(data: dict) -> None: |
20 |
| - json_file = Path("data.json") |
| 16 | +def run_json(data: dict, json_file: Path, only_create: bool = False) -> None: |
21 | 17 | json_str = json.dumps(data, ensure_ascii=False, indent=4)
|
22 | 18 |
|
23 | 19 | # Crear fichero:
|
24 | 20 | json_file.write_text(json_str, encoding="utf-8")
|
25 | 21 |
|
| 22 | + if only_create: |
| 23 | + return |
| 24 | + |
26 | 25 | # Mostrar fichero:
|
27 | 26 | print(json_file.read_text())
|
28 | 27 |
|
29 | 28 | # Borrar fichero:
|
30 | 29 | json_file.unlink()
|
31 | 30 |
|
32 | 31 |
|
33 |
| -def run_xml(data: dict) -> None: |
34 |
| - xml_file = Path("data.xml") |
35 |
| - |
36 |
| - root = ET.Element("persona") |
| 32 | +def run_xml(data: dict, xml_file: Path, only_create: bool = False) -> None: |
| 33 | + root = tree.Element("persona") |
37 | 34 |
|
38 | 35 | for k, v in data.items():
|
39 |
| - element = ET.SubElement(root, k) |
| 36 | + element = tree.SubElement(root, k) |
40 | 37 | if isinstance(v, list):
|
41 | 38 | for sub in v:
|
42 |
| - sub_element = ET.SubElement(element, "item") |
| 39 | + sub_element = tree.SubElement(element, "item") |
43 | 40 | sub_element.text = sub
|
44 | 41 | else:
|
45 | 42 | element.text = str(v)
|
46 | 43 |
|
47 |
| - ET.indent(root) # for pretty output |
48 |
| - xml_str = ET.tostring(root, encoding="utf-8") |
| 44 | + tree.indent(root) # for pretty output |
| 45 | + xml_str = tree.tostring(root, encoding="utf-8") |
49 | 46 |
|
50 | 47 | # Crear fichero:
|
51 | 48 | xml_file.write_bytes(xml_str)
|
52 | 49 |
|
| 50 | + if only_create: |
| 51 | + return |
| 52 | + |
53 | 53 | # Mostrar fichero:
|
54 | 54 | print(xml_file.read_text())
|
55 | 55 |
|
56 | 56 | # Borrar fichero:
|
57 | 57 | xml_file.unlink()
|
58 | 58 |
|
59 | 59 |
|
| 60 | +def extra(data: dict): |
| 61 | + |
| 62 | + for file_format in ("json", "xml"): |
| 63 | + file = Path(f"data.{file_format}") |
| 64 | + parser = JsonAndXML(file, file_format=file_format) |
| 65 | + parser.write_file(data) |
| 66 | + parser.read_file() |
| 67 | + parser.modify_data() |
| 68 | + parser.write_file() |
| 69 | + print(parser.file.read_text(encoding="utf-8")) |
| 70 | + parser.file.unlink() |
| 71 | + |
| 72 | + |
| 73 | +class JsonAndXML: |
| 74 | + |
| 75 | + def __init__(self, file: Path, file_format: str = "json"): |
| 76 | + self.file = file |
| 77 | + self.file_format = file_format |
| 78 | + self.data = None |
| 79 | + |
| 80 | + def write_file(self, data: Optional[dict] = None, file_format: Optional[str] = None) -> None: |
| 81 | + data = data or self.data |
| 82 | + file_format = file_format or self.file_format |
| 83 | + |
| 84 | + if file_format == "json": |
| 85 | + run_json(data, self.file, only_create=True) |
| 86 | + elif file_format == "xml": |
| 87 | + run_xml(data, self.file, only_create=True) |
| 88 | + else: |
| 89 | + raise ValueError(f"No conozco el formato {file_format}") |
| 90 | + |
| 91 | + def read_file(self, file_format: Optional[str] = None) -> None: |
| 92 | + file_format = file_format or self.file_format |
| 93 | + |
| 94 | + if not self.file.is_file(): |
| 95 | + print(f"No pudimos leer el fichero '{self.file}'. No existe.") |
| 96 | + return |
| 97 | + |
| 98 | + if file_format == "json": |
| 99 | + self.data = json.loads(self.file.read_text(encoding="utf-8")) |
| 100 | + elif file_format == "xml": |
| 101 | + root = tree.parse(self.file).getroot() |
| 102 | + |
| 103 | + self.data = {} |
| 104 | + for child in root: |
| 105 | + self.data[child.tag] = child.text |
| 106 | + values = [c.text for c in child] |
| 107 | + if values: |
| 108 | + self.data[child.tag] = values |
| 109 | + else: |
| 110 | + raise ValueError(f"No conozco el formato {file_format}") |
| 111 | + |
| 112 | + def modify_data(self): |
| 113 | + if not self.data: |
| 114 | + return |
| 115 | + self.data["nombre"] = "Henry Cavill" |
| 116 | + |
| 117 | + |
60 | 118 | if __name__ == "__main__":
|
61 |
| - main() |
| 119 | + persona = { |
| 120 | + "nombre": "Iñaki Silanes", |
| 121 | + "edad": 46, |
| 122 | + "fecha_de_nacimiento": datetime(1977, 6, 11, 9, 0).isoformat(), |
| 123 | + "lenguajes_de_programación": ["python", "bash", "perl", "fortran", "javascript"], |
| 124 | + } |
| 125 | + |
| 126 | + main(data=persona) |
| 127 | + extra(data=persona) |
0 commit comments