Skip to content

Commit 8bda1e8

Browse files
authored
Merge pull request mouredev#2533 from isilanes/reto-012
#12 - Python
2 parents 0a0d600 + 0c998b1 commit 8bda1e8

File tree

1 file changed

+127
-0
lines changed

1 file changed

+127
-0
lines changed
+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import json
2+
from datetime import datetime
3+
from pathlib import Path
4+
import xml.etree.ElementTree as tree
5+
from typing import Optional
6+
7+
8+
def main(data: dict) -> None:
9+
json_file = Path("data.json")
10+
run_json(data, json_file)
11+
12+
xml_file = Path("data.xml")
13+
run_xml(data, xml_file)
14+
15+
16+
def run_json(data: dict, json_file: Path, only_create: bool = False) -> None:
17+
json_str = json.dumps(data, ensure_ascii=False, indent=4)
18+
19+
# Crear fichero:
20+
json_file.write_text(json_str, encoding="utf-8")
21+
22+
if only_create:
23+
return
24+
25+
# Mostrar fichero:
26+
print(json_file.read_text())
27+
28+
# Borrar fichero:
29+
json_file.unlink()
30+
31+
32+
def run_xml(data: dict, xml_file: Path, only_create: bool = False) -> None:
33+
root = tree.Element("persona")
34+
35+
for k, v in data.items():
36+
element = tree.SubElement(root, k)
37+
if isinstance(v, list):
38+
for sub in v:
39+
sub_element = tree.SubElement(element, "item")
40+
sub_element.text = sub
41+
else:
42+
element.text = str(v)
43+
44+
tree.indent(root) # for pretty output
45+
xml_str = tree.tostring(root, encoding="utf-8")
46+
47+
# Crear fichero:
48+
xml_file.write_bytes(xml_str)
49+
50+
if only_create:
51+
return
52+
53+
# Mostrar fichero:
54+
print(xml_file.read_text())
55+
56+
# Borrar fichero:
57+
xml_file.unlink()
58+
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+
118+
if __name__ == "__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)