How to add multiple dictionaries using the pickle to save in txt

0

I have the problem when saving a file using the pickle module, every time I run the program it rewrites the existing dictionary. I already tried to use shelve to replace it but I did not get an exite.

Below is part of the algorithm for better understanding.

aluno = {'nome': str (nome), 'nota1':float(nota1), 'nota2':float(nota2), 'media': float(media), 'resultado': str(resultado)}
escola[aluno['nome']] = aluno
bancodd = open('escola_banco.txt', 'wb') #abrindo arquivo para modo de edicao
pickle.dump(escola,bancodd) #salvando arquivos
bancodd.close()
print ('Dados do aluno',nome,'salvos',)
    
asked by anonymous 07.11.2017 / 06:07

2 answers

0

If you do not read the original file, it will always write a new dictionary.

At the beginning of your program, you have to read the file on the disk to a dictionary in memory, work with it, update it, etc ... and at the time of closing the program, save the dictionary in the disk.

This dictionary on disk will always be a new dictionary created from scratch. Are there ways you can not rewrite everything? But it 's absolutely not worth it. A dictionary with 10000 names will be written in a time around 1 second on the disk, and the complications to keep everything synchronized would be several.

The alternative to this flow of reading everything to memory, to work and to write back is to use a database - be it traditional SQL (and Python comes with sqlite, does not need to install or configure anything), be a NoSQL database more simple as redis - which works almost like a "live" dictionary.

Now, one thing you'll need to do is group your code in functions . You've probably learned about them, so it's time to start exercising what you've learned. Having a function that reads the dictionary and one that writes the dictionary into the file, you can do this anytime you wish, with just one line of code. So the rest of the application can grow to have student inclusion menus, change notes, etc ... and you just need to call the function that saves the dictionary, with the whole code in one place.

    
07.11.2017 / 17:09
1

You are copying only a reference from your dictionary.

To make an identical duplicate of your dictionary use the deepcopy() function of the copy :

import copy
...
escola[aluno['nome']] = copy.deepcopy(aluno)
...
    
07.11.2017 / 11:56