My program consists of adding elements to a binary file using a function, the opening mode of the binary file is in "a+b" so it should be added to the end of the already existing file, but my problem is that it is not being added correctly the content to the file but it overwrites an object (in case of already having an object), so that it does not let me have more than 1 object in the binary file. I thought and it is also likely that I had an error printing the content of the binary file, my code is as follows:
import os
import pickle
class Temas():
def __init__(self,autor,title):
self.autor=autor
self.titulo=title
def Agregar(temas):
archivo=open("InventarioMusica.dat","a+b")
print("Ingrese nombre del autor y titulo del tema que desea agregar")
title=input("Titulo: ")
autor=input("Autor: ")
temas.append(Temas(autor,title))
os.system("cls")
pickle.dump(temas,archivo)
print("El tema fue agregado con exito")
os.system("pause")
archivo.close()
def Visualizar():
print("Los temas en el sistemas son los siguientes: ")
if os.stat("InventarioMusica.dat").st_size == 0:
print("» No se tiene ningun tema en el sistema")
else:
archivo=open("InventarioMusica.dat","rb")
contenido=pickle.load(archivo)
archivo.close()
for i in contenido:
print("» TItulo: ",i.titulo)
print("» Autor: ",i.autor)
os.system("pause")
def Eliminar():
pass
temas=[]
while True:
os.system("color 0f")
print("Inventario de Temas Musicales:")
print("» Ingrese 1 para agregar un tema nuevo")
print("» Ingrese 2 para visualizar los temas del inventario")
print("» Ingrese 3 para Borrar un determinado tema (busqueda por titulo)")
print("» Ingrese 4 para terminar")
opc=int(input("Opcion: "))
os.system("cls")
if opc == 1:
Agregar(temas)
elif opc == 2:
Visualizar()
elif opc == 3:
Eliminar()
elif opc == 4:
break
else:
os.system("color 4f")
print("Se introdujo un valor fuera de las opciones")
os.system("pause")
os.system("cls")
My other problem is to delete a certain object from the file, I am not very clear how to code the elimination of a certain content, this is the function that I have incomplete:
def Eliminar():
encontro=False
print("Ingrese a continuacion, titulo del tema que desea Eliminar")
delete=input("Titulo: ")
os.system("cls")
#se ingresa por teclado en la variable "delete" el nombre del titulo a eliminar
It is the first time that I am working with binary files, I searched but I did not find a solution to these problems.
I've been looking at your code, and you have several problems.
Agregar(temas)
temas
it is always empty, since it was declared as such.ab
: It means to add new value/object at the end of the file in binary mode (but remember we need to keep a list type structure) sowb
(overwrite all) is the most suitable.On the other hand, I recommend dividing the code into functions, for example, listing all the data could be a function or saving new data.
The part of deleting a theme is easy, the idea is simply to search the themes for the theme that you make
match
with the title that has been entered by keyboard.I've made a few changes to your code, which not only looks cleaner but is also simpler to maintain and make a change if needed.
That said, the end result would be something like this
Hope this can help you.
All the best.
There is a problem with the recording code:
topics is a list that always grows; it never loses elements or is empty. Every time you do a
pickle.dump
you are recording the entire list. Since you opened the file in "a+b" mode, this list you saved is added to the queue of previous lists.That is, the file is like this (starting from an empty file). Each line corresponds to a
pickle.dump()
:When you try to read back the list of topics,
pickle.load
it only loads the first object in the file, which is a list with a single topic. That's why it looks like the file only contains one item.Each time you run
pickle.load
a new object is loaded from the file, so you would eventually get to the latest version of the playlist.The healthiest thing, however, is to open the file in "w+b" mode. The "w" mode erases anything from before. The asi file only contains the latest version of the playlist, and just one is enough
pickle.load
to retrieve the latest version.The deletion problem
Remove it from the theme list and then save the list to file, just like you do when adding a theme.