Answer the question
In order to leave comments, you need to log in
How to add a dictionary to a file using the pickle module?
How to add a dictionary to a file using the pickle module?
And so that later this dictionary can be called in the code by the keys. And at the same time, the dictionary should be filled through input.
I'm new to Python so I apologize if the question is banal or inappropriate, below is the code I tried to do this.
import pickle
users_choise = input("Желаете получить или ввести информацию - ")
file_name = 'Список.txt'
ff = open(file_name, 'rb')
baza = {ff}
if users_choise == 'ввести':
for i in range(1):
users_name = input("Введите имя - ")
users_numbe = input("Введите номер - ")
baza.update({users_name.title():users_numbe})
print("Контакт добавлен !")
file = 'Список.txt'
f = open(file, 'wb')
pickle.dump(baza, f)
f.close
elif users_choise == 'получить':
users_input_name = input("Введите имя контакта - ")
data = baza.get(users_input_name)
print(data)
users_doing = input(" Желаете закончить выполнения программы ? - ")
if users_doing == 'Да':
print('Програма закрыта ', end = ' ')
elif users_doing == 'Нет':
print(users_choise)
Answer the question
In order to leave comments, you need to log in
Well, for starters, I would suggest using json instead of pickle. pickle gives a binary string that is not human readable. In addition, as it is written in big red letters in the docks on pickle, it has vulnerabilities, so in no case should you pass untrusted data through it.
There are a lot of crooked calls in the code that are not relevant.
ff = open(file_name, 'rb')
baza = {ff}
import json
#оператор with обеспечит закрытие файла, как только управление покинет тело оператора
#явное указание кодировки подстрахует от получения "кракозябр" на выходе
#Кодировка utf-8 позволит использовать символы любых алфавитов.
with open('Список.txt', 'rt', encoding='utf-8') as ff:
baza = json.load(ff)
baza.update({users_name.title():users_numbe})
baza[users_name.title()] = users_numbe
f.close
with open('Список.txt', 'wt', encoding='utf-8') as ff:
json.dump(
baza, #что записываем
ff, #куда
ensure_ascii=False, #не ASCII-строки пишем как есть, без кодирования
indent=" ", #сделать отступ, не писать всё в одну строку
sort_keys=True, #отсортировать ключи по алфавиту
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question