V
V
Viktor2021-07-06 18:33:37
Python
Viktor, 2021-07-06 18:33:37

The snake does not want to extract the dictionary from the *.txt file, how can I help it?

There is a db.txt file that contains only one line^

{'000000': {'name': 'patient_zero', 'bank': 500}, '111111': {'name': 'Badmajor', 'bank': 1000}, '222222': {'name': 'Badmajor1', 'bank': 1000}}


And the code, which theoretically can pull out a dictionary, but it lacks something, gives an error about lowercase indexes. But if you just insert a line into the code, it reads like a dictionary.
with open('db.txt', 'r', encoding='utf-8') as db:
    db_dict = db.read()
    user_data = db_dict['000000']
    name_user = user_data['name']
    print(name_user)

Mistake:
Traceback (most recent call last):
File "\main.py", line 5, in
user_data = db_dict['000000']
TypeError: string indices must be integers


How to be, what to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-07-06
@Badmajor

theoretically can pull out a dictionary

And practically it reads a line.
Or via json
import json

with open('db.txt', 'r', encoding='utf-8') as db:
    db_dict = json.load(db)

Either through literal_eval, although json is, of course, better

P
PRoGRamm_InG, 2021-07-06
@PRoGRamm_InG

You need to save the dictionary as .data
For example:

import pickle
# имя файла, в котором мы сохраним объект
shoplistfile = 'shoplist.data'
shoplist = ['яблоки', 'манго', 'морковь']
# Запись в файл
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f) # помещаем объект в файл
f.close()
del shoplist # уничтожаем переменную shoplist

You can pull it out like this:
# Считываем из хранилища
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f) # загружаем объект из файла

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question