Skip to content

Commit 0c998b1

Browse files
committed
[reto-012] Implementada funcionalidad extra
1 parent cf2101c commit 0c998b1

File tree

1 file changed

+87
-21
lines changed

1 file changed

+87
-21
lines changed
+87-21
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,127 @@
11
import json
22
from datetime import datetime
33
from pathlib import Path
4-
import xml.etree.ElementTree as ET
4+
import xml.etree.ElementTree as tree
5+
from typing import Optional
56

67

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)
1411

15-
run_json(data)
16-
run_xml(data)
12+
xml_file = Path("data.xml")
13+
run_xml(data, xml_file)
1714

1815

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:
2117
json_str = json.dumps(data, ensure_ascii=False, indent=4)
2218

2319
# Crear fichero:
2420
json_file.write_text(json_str, encoding="utf-8")
2521

22+
if only_create:
23+
return
24+
2625
# Mostrar fichero:
2726
print(json_file.read_text())
2827

2928
# Borrar fichero:
3029
json_file.unlink()
3130

3231

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")
3734

3835
for k, v in data.items():
39-
element = ET.SubElement(root, k)
36+
element = tree.SubElement(root, k)
4037
if isinstance(v, list):
4138
for sub in v:
42-
sub_element = ET.SubElement(element, "item")
39+
sub_element = tree.SubElement(element, "item")
4340
sub_element.text = sub
4441
else:
4542
element.text = str(v)
4643

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")
4946

5047
# Crear fichero:
5148
xml_file.write_bytes(xml_str)
5249

50+
if only_create:
51+
return
52+
5353
# Mostrar fichero:
5454
print(xml_file.read_text())
5555

5656
# Borrar fichero:
5757
xml_file.unlink()
5858

5959

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+
60118
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

Comments
 (0)