How to register data in a dictionary within a . txt file?

Asked

Viewed 147 times

0

I’m running a registration system, which records a person’s user and password in a dictionary and then passes that dictionary to a .txt. See the example:

user = 'Lucas'
password = '1234'`

dic = {}
dic[user] = password`

import pickle
archive = open('data.txt', 'ab')
pickle.dump(dic, archive)
archive.close()`

archive = open('data.txt', 'rb')
dic = pickle.load(archive)
archive.close()
print(dic)

The problem is that my program will register infinite users and forever, so if I now put another user and another password it should return a dictionary with all registered users + the user being registered, that is, add the last entry to the already saved dictionary with previous users, only that it is saving a dictionary only with the last registered user. How could you solve?

  • 1

    You are always defining a new dictionary, dic. To do this, you will need to load the dictionary from the file before entering the new registration.

  • How could I do that Woss?

  • 1

    You’ve already done it in the code, just analyze and understand well what you wrote in the code.

1 answer

2

Json is a much better format for saving serialized data. Pickle has several security and compatibility issues.

# Considerações:
# 1) Isso não é um sistema de login
# 2) Armazenar usuário e senha em um arquivo de texto ou em pickle é um trabalho super porco
from json import dumps, loads

dic = {'Lucas': '1234'}

# Serializando os dados em json e salvando em um arquivo de texto
with open("data.txt", "w") as f:
    f.write(dumps(dic))

# Lendo dados serializados em json
with open("data.txt", "r") as f:
    dic_deserializado = loads(f.read())


# Adicionando mais entradas e salvando
dic_deserializado.update({'Xablaus': '4321'})
with open("data.txt", "w") as f:
    f.write(dumps(dic_deserializado))

Browser other questions tagged

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