Skip to content

Commit 40b6703

Browse files
authored
Merge pull request mouredev#7184 from Dkp-Dev/main
#11 - Python
2 parents 2af3028 + 5ee5e22 commit 40b6703

File tree

2 files changed

+231
-0
lines changed

2 files changed

+231
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import os
2+
3+
"""
4+
* EJERCICIO:
5+
* Desarrolla un programa capaz de crear un archivo que se llame como
6+
* tu usuario de GitHub y tenga la extensión .txt.
7+
* Añade varias líneas en ese fichero:
8+
* - Tu nombre.
9+
* - Edad.
10+
* - Lenguaje de programación favorito.
11+
* Imprime el contenido.
12+
* Borra el fichero.
13+
"""
14+
15+
file_name = "Dkp-Dev.txt"
16+
17+
with open(file_name, "w") as file:
18+
file.write("Dkp Dev\n")
19+
file.write("29\n")
20+
file.write("Python")
21+
22+
with open(file_name, "r") as file:
23+
print(file.read())
24+
25+
os.remove(file_name)
26+
27+
"""
28+
* DIFICULTAD EXTRA (opcional):
29+
* Desarrolla un programa de gestión de ventas que almacena sus datos en un
30+
* archivo .txt.
31+
* - Cada producto se guarda en una línea del archivo de la siguiente manera:
32+
* [nombre_producto], [cantidad_vendida], [precio].
33+
* - Siguiendo ese formato, y mediante terminal, debe permitir añadir, consultar,
34+
* actualizar, eliminar productos y salir.
35+
* - También debe poseer opciones para calcular la venta total y por producto.
36+
* - La opción salir borra el .txt.
37+
*/
38+
"""
39+
40+
file_name = "Dkp-Dev Shop.txt"
41+
42+
open(file_name, "a")
43+
44+
while True:
45+
print("1. Añadir producto")
46+
print("2. Consultar producto")
47+
print("3. Actualizar producto")
48+
print("4. Borrar producto")
49+
print("5. Mostrar productos")
50+
print("6. Calcular venta total")
51+
print("7. Calcular venta por producto")
52+
print("8. Salir")
53+
54+
option = input("Selecciona una opción: ")
55+
56+
if option == "1":
57+
name = input("Nombre: ")
58+
quantity = input("Cantidad: ")
59+
price = input("Precio: ")
60+
with open(file_name, "a") as file:
61+
file.write(f"{name}, {quantity}, {price}\n")
62+
elif option == "2":
63+
name = input("Nombre: ")
64+
with open(file_name, "r") as file:
65+
for line in file.readlines():
66+
if line.split(", ")[0] == name:
67+
print(line)
68+
break
69+
elif option == "3":
70+
name = input("Nombre: ")
71+
quantity = input("Cantidad: ")
72+
price = input("Precio: ")
73+
with open(file_name, "r") as file:
74+
lines = file.readlines()
75+
with open(file_name, "w") as file:
76+
for line in lines:
77+
if line.split(", ")[0] == name:
78+
file.write(f"{name}, {quantity}, {price}\n")
79+
else:
80+
file.write(line)
81+
elif option == "4":
82+
name = input("Nombre: ")
83+
with open(file_name, "r") as file:
84+
lines = file.readlines()
85+
with open(file_name, "w") as file:
86+
for line in lines:
87+
if line.split(", ")[0] != name:
88+
file.write(line)
89+
elif option == "5":
90+
with open(file_name, "r") as file:
91+
print(file.read())
92+
elif option == "6":
93+
total = 0
94+
with open(file_name, "r") as file:
95+
for line in file.readlines():
96+
components = line.split(", ")
97+
quantity = int(components[1])
98+
price = float(components[2])
99+
total += quantity * price
100+
print(total)
101+
elif option == "7":
102+
name = input("Nombre: ")
103+
total = 0
104+
with open(file_name, "r") as file:
105+
for line in file.readlines():
106+
components = line.split(", ")
107+
if components[0] == name:
108+
quantity = int(components[1])
109+
price = float(components[2])
110+
total += quantity * price
111+
break
112+
print(total)
113+
elif option == "8":
114+
os.remove(file_name)
115+
break
116+
else:
117+
print("Selecciona una de las opciones disponibles.")
+114
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import os
2+
import xml.etree.ElementTree as xml
3+
import json
4+
5+
data = {
6+
"name": "Dkp Dev",
7+
"age": 29,
8+
"birth_date": "11-01-1995",
9+
"programming_languages": ["Python", "Kotlin", "Java"]
10+
}
11+
12+
xml_file = "dkp-dev.xml"
13+
json_file = "dkp-dev.json"
14+
15+
"""
16+
EJERCICIO:
17+
* Desarrolla un programa capaz de crear un archivo XML y JSON que guarde los
18+
* siguientes datos (haciendo uso de la sintaxis correcta en cada caso):
19+
* - Nombre
20+
* - Edad
21+
* - Fecha de nacimiento
22+
* - Listado de lenguajes de programación
23+
* Muestra el contenido de los archivos.
24+
* Borra los archivos.
25+
"""
26+
27+
# XML
28+
29+
30+
def create_xml():
31+
32+
root = xml.Element("data")
33+
34+
for key, value in data.items():
35+
child = xml.SubElement(root, key)
36+
if isinstance(value, list):
37+
for item in value:
38+
xml.SubElement(child, "item").text = item
39+
else:
40+
child.text = str(value)
41+
42+
tree = xml.ElementTree(root)
43+
tree.write(xml_file)
44+
45+
46+
create_xml()
47+
48+
with open(xml_file, "r") as xml_data:
49+
print(xml_data.read())
50+
51+
os.remove(xml_file)
52+
53+
# JSON
54+
55+
56+
def create_json():
57+
with open(json_file, "w") as json_data:
58+
json.dump(data, json_data)
59+
60+
61+
create_json()
62+
63+
with open(json_file, "r") as json_data:
64+
print(json_data.read())
65+
66+
os.remove(json_file)
67+
68+
"""
69+
DIFICULTAD EXTRA (opcional):
70+
* Utilizando la lógica de creación de los archivos anteriores, crea un
71+
* programa capaz de leer y transformar en una misma clase custom de tu
72+
* lenguaje los datos almacenados en el XML y el JSON.
73+
* Borra los archivos.
74+
"""
75+
76+
create_xml()
77+
create_json()
78+
79+
80+
class Data:
81+
82+
def __init__(self, name, age, birth_date, programming_languages) -> None:
83+
self.name = name
84+
self.age = age
85+
self.birth_date = birth_date
86+
self.programming_languages = programming_languages
87+
88+
89+
with open(xml_file, "r") as xml_data:
90+
91+
root = xml.fromstring(xml_data.read())
92+
name = root.find("name").text
93+
age = root.find("age").text
94+
birth_date = root.find("birth_date").text
95+
programming_languages = []
96+
for item in root.find("programming_languages"):
97+
programming_languages.append(item.text)
98+
99+
xml_class = Data(name, age, birth_date, programming_languages)
100+
print(xml_class.__dict__)
101+
102+
103+
with open(json_file, "r") as json_data:
104+
json_dict = json.load(json_data)
105+
json_class = Data(
106+
json_dict["name"],
107+
json_dict["age"],
108+
json_dict["birth_date"],
109+
json_dict["programming_languages"]
110+
)
111+
print(json_class.__dict__)
112+
113+
os.remove(xml_file)
114+
os.remove(json_file)

0 commit comments

Comments
 (0)