Skip to content

Commit

Permalink
Merge pull request mouredev#6834 from JheisonQuiroga/main
Browse files Browse the repository at this point in the history
mouredev#11 - Python
  • Loading branch information
Roswell468 authored Nov 2, 2024
2 parents 7f602ce + 0eef663 commit afed3d0
Show file tree
Hide file tree
Showing 2 changed files with 251 additions and 0 deletions.
136 changes: 136 additions & 0 deletions Roadmap/11 - MANEJO DE FICHEROS/python/JheisonQuiroga.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import os

text = """Jheison Duban Quiroga Quintero
26
Python"""

with open("JheisonQuiroga.txt", "w") as f:
f.write(text)

file = "JheisonQuiroga.txt"

with open(file) as f:
if os.path.exists("./JheisonQuiroga.txt"):
text = f.read()
print(text)
else:
print("The file is not exists")


""" Extra """

my_file = "sells.txt"
products = []


def add_product(name:str, sell_total:int, price:int):
if not os.path.exists(my_file):
with open(my_file, "x") as file:
file.write(f"{name}, {sell_total}, {price}\n")
products.append({
"name": name,
"sell_total": sell_total,
"price": price
})
else:
with open(my_file, "a") as file:
file.write(f"{name}, {sell_total}, {price}\n")
products.append({
"name": name,
"sell_total": sell_total,
"price": price
})


def get_info():
print("-" * 5, "Inventario", "-" * 5)
for dct in products:
print(f"{dct['name']}, {dct['sell_total']}, {dct['price']}")


def update(name, new_item_sell, new_price):
with open(my_file, "w") as file:
for product in products:
if product["name"] == name:
product["sell_total"] = new_item_sell
product["price"] = new_price
file.write(f"{product["name"]}, {product["sell_total"]}, {product["price"]}\n")

def remove_products(name):
global products # Para asegurarme de borrar la lista original

filter_products = [product for product in products if product["name"] != name]

products = filter_products
# Sobreescribe el archivo con los productos filtrados
with open(my_file, "w") as file:
for product in products:
file.write(f"{product['name']}, {product['sell_total']}, {product['price']}\n")

def get_product():
name = input("Nombre del producto: ")
item_sell = int(input("Total de ventas: "))
price = int(input("Precio: "))
return name, item_sell, price

def sales_calculate():
global products
total_sales = 0
for product in products:
total_sale_per_product = product["sell_total"] * product["price"]
total_sales += total_sale_per_product

return total_sales

def remove_file(): # Funcion para borrar archivo al salir
if os.path.exists(my_file):
os.remove(my_file)
print("El archivo ha sido borrado!")


def main():

while True:
option = int(input("""----- Sistema de Gestión de ventas -----
1. Agregar producto
2. Consultar inventario
3. Actualizar
4. Eliminar producto
5. Total ventas
6. Venta por producto
7. Salir
Elige una opcion: """))

match option:
case 1:
name, item_sell, price = get_product()
add_product(name, item_sell, price)
case 2:
get_info()
case 3:
name, item_sell, price = get_product()
update(name, item_sell, price)
case 4:
name = input("Ingrese el nombre del producto a eliminar")
remove_products(name)
case 5:
print(sales_calculate())
case 6:
name = input("Nombre del producto: ")
with open(my_file, "r") as file:
for line in file.readlines():
components = line.split(", ")
if name == components[0]:
quantity = int(components[1])
price = int(components[2])
total = quantity * price
print(total)
break

case 7:
remove_file()
print("Saliendo del programa...")
return


main()
115 changes: 115 additions & 0 deletions Roadmap/12 - JSON Y XML/python/JheisonQuiroga.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import json
import os
import xml.etree.ElementTree as ET

# json extension

dct = {
"firstname": "Duban",
"lastname": "Quiroga",
"country": "Colombia",
"skills": [
"Python", "Java"
]
}

def file_creates_and_read(path:str, dct:dict) -> str:

with open("./jsonfile.json", "w") as file:
json.dump(dct, file, indent=4)


#with open("./jsonfile.json") as file:
# content = json.load(file)
#os.remove(path)
#return json.dumps(content, indent=4)


print(file_creates_and_read("jsonfile.json", dct))

# XML extension

def create_file():
# Crear el elemento raiz
root = ET.Element("person")

# Añadir subelementos
firstname = ET.SubElement(root, "firstname")
firstname.text = "Duban"

lastname = ET.SubElement(root, "lastname")
lastname.text = "Quiroga"

country = ET.SubElement(root, "country")
country.text = "Colombia"

# Se crea un subelemento para los skills con una lista de lenguajes
skills = ET.SubElement(root, "skills")
skill1 = ET.SubElement(skills, "skill")
skill1.text = "Python"
skill2 = ET.SubElement(skills, "skill")
skill2.text = "Java"

# Se guarda el archivo
tree = ET.ElementTree(root)
with open("person.xml", "wb") as f:
tree.write(f)

def show_content():
#Mostrar el contenido del archivo
print("-" * 5, "Contenido del archivo XML", "-" * 5)
tree = ET.parse("person.xml")
root = tree.getroot()
for element in root:
if element.tag == "skills":
print("Skills: ", [skill.text for skill in element])
else:
print(f"{element.tag.capitalize()}: {element.text}")

def remove_file():
# Eliminar archivo
if os.path.exists("person.xml"):
os.remove("person.xml")
else:
print("El archivo no existe")


""" Extra """

create_file()


class Custom:

def __init__(self, fname, lname, country, skills):
self.fname = fname
self.lname = lname
self.country = country
self.skills = skills

file_name = "jsonfile.json"
xml_file = "person.xml"

with open(file_name) as file:
content = file.read()
data_json = json.loads(content)
person_json = Custom(data_json["firstname"], data_json["lastname"], data_json["country"], data_json["skills"])


print(person_json.__dict__)

with open(xml_file, "r") as file:
data = file.read()
root = ET.fromstring(data)
fname = root.find("firstname").text
lname = root.find("lastname").text
country = root.find("country").text
skills = []
for skill in root.find("skills"):
skills.append(skill.text)

person_xml = Custom(fname, lname, country, skills)
print(person_xml.__dict__) # Datos en formato diccionario

os.remove(file_name)
os.remove(xml_file)

0 comments on commit afed3d0

Please sign in to comment.