How to add multiple dictionaries using pickle to save to txt

Asked

Viewed 335 times

0

I’m having trouble saving a file using the pickle module, every time I run the program it rewrites over the existing dictionary. I tried to use the shelve to sub-post but I didn’t get a hit.

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',)

2 answers

1

You’re just copying a reference from your dictionary.

To make a identical duplicate from your dictionary use the function deepcopy() module copy:

import copy
...
escola[aluno['nome']] = copy.deepcopy(aluno)
...
  • I tried to use this way with copy but still it writes on top of the already saved txt file.

0


If you don’t read the original file, it will always write a new dictionary.

You have to, at the beginning of the execution of your program, read the file that is on the disk to a dictionary in memory, work with it, update, etc...and at the time of terminating the program, write the dictionary on the disk.

This dictionary on disk will always be a new dictionary created from scratch. Do you have ways to not rewrite everything? It has - but absolutamnte is 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 stream of reading everything to memory, working and writing back is to use a database - be it traditional SQL (and Python comes with sqlite, you don’t need to install or configure anything), be it a simpler Nosql database like redis - which works almost like a dictionary "alive".

Now, one thing you’ll need to do is group your code into function . You’ve probably already 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 in the file, you can do it anytime you want, with just one line of code. Da'i the rest of the application can grow to have student inclusion menus, change grades, etc.... and you only need to call the function that records the dictionary, with the whole code in one place.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.