H
H
hlystik2021-11-05 17:46:44
Python
hlystik, 2021-11-05 17:46:44

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

1 answer(s)
V
Vindicar, 2021-11-05
@hlystik

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}

What is this supposed to mean anyway? You created a set from one element - file object ff. Or did you expect it to magically turn the file into a dictionary?
How to:
import json 
#оператор with обеспечит закрытие файла, как только управление покинет тело оператора
#явное указание кодировки подстрахует от получения "кракозябр" на выходе
#Кодировка utf-8 позволит использовать символы любых алфавитов.
with open('Список.txt', 'rt', encoding='utf-8') as ff:
    baza = json.load(ff)

Further.
baza.update({users_name.title():users_numbe})
What for? Why not simply write:
baza[users_name.title()] = users_numbe
Next.
f.close
You took the address of the close method from object f. You have NOT called the close method. To call a method, you need to specify parentheses. However, if you use with, it will call close() for you.
So that:
with open('Список.txt', 'wt', encoding='utf-8') as ff:
    json.dump(
        baza, #что записываем
        ff, #куда
        ensure_ascii=False, #не ASCII-строки пишем как есть, без кодирования
        indent="    ", #сделать отступ, не писать всё в одну строку
        sort_keys=True, #отсортировать ключи по алфавиту
    )

The rest is about the same.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question