saving Dict list on file

Asked

Viewed 53 times

1

I have a function that saves a Dict in a file, but this is simultaneous, I mean, every time I have a new Dict. I couldn’t apply the concept of append to this problem.

The Archive is being saved this way:

 {
"num_conta": "11_OPEN.json",
"item_num": "333",
"item_desc": "COCA 3",
"item_price": "5.00"
 }
{
"num_conta": "11_OPEN.json",
"item_num": "222",
"item_desc": "FRANGO PEDACO",
"item_price": "5.00"
 }

I wish it was a list of Icts, that way:

[
{
"num_conta": "11_OPEN.json",
"item_num": "333",
"item_desc": "COCA 3",
"item_price": "5.00"
 }, 
{
"num_conta": "11_OPEN.json",
"item_num": "222",
"item_desc": "FRANGO PEDACO",
"item_price": "5.00"
 }
]

My Class

class Conta:
     def __init__(self, num_conta, item_num, item_desc, item_price):
       self.num_conta = num_conta
       self.item_num = item_num
       self.item_desc = item_desc
       self.item_price = item_price

And here’s my job to save the file:

if not os.path.exists('data/today/CHECK/' + conta.num_conta):
    with open('data/today/CHECK/' + conta.num_conta, 'w') as arquivo:
        json.dump(conta.__dict__, arquivo, indent=4)
        arquivo.close()
else:
    arquivo = open('data/today/CHECK/' + conta.num_conta, 'a')
    # json_string = json.dumps(data_request)
    json.dump(conta.__dict__, arquivo, indent=4)
    arquivo.close()

Any help is good life, thank you.

2 answers

0

Well, one possible solution is to use the Garbage collector to take the dictionary of each instance of your class, add these dictionaries to a list and save the list with pickle. See:

import gc
import pickle

class Conta:
     def __init__(self, num_conta, item_num, item_desc, item_price):
       self.num_conta = num_conta
       self.item_num = item_num
       self.item_desc = item_desc
       self.item_price = item_price

conta1 = Conta(1,2,3,4)
conta2 = Conta(3,5,7,9)

#criando uma lista de dicionários das instâncias da classe Conta

lista_instancia =[]
for obj in gc.get_objects():
    if isinstance(obj, Conta):
        lista_instancia.append(obj.__dict__)

print(lista_instancia)

Output:

[{'num_conta': 1, 
'item_num': 2, 
'item_desc': 3, 
'item_price': 4},
{'num_conta': 3, 
'item_num': 5, 
'item_desc': 7, 
'item_price': 9}]

Saving:

f = open('minha_lista.pkl', 'wb')
pickle.dump(lista_instancia, f)
f.close()
  • 1

    Hi Lucas, thank you so much for the answer, I managed to solve in a simpler way but I do not know if it is the most platonic way. I’m posting the code with the explanation.

0


I managed to solve my problem as follows: Save the first item as a Dict list:

if not os.path.exists('data/today/CHECK/' + conta.num_conta):
    print('Arquivo Json não existe')
    lista_instancia = [conta.__dict__]
    with open('data/today/CHECK/' + conta.num_conta, 'w') as arquivo:
        json.dump(lista_instancia, arquivo, ensure_ascii=False, indent=4)
        arquivo.close()

If the file already exists, I prompt the file item, add the rest in a new list and saved, the output is the one I posted in the question.

    else:
    arquivo = open('data/today/CHECK/' + conta.num_conta).read()
    objeto_json = json.loads(arquivo)
    objeto_json.append(conta.__dict__)
    arquivo_new = open('data/today/CHECK/' + conta.num_conta, 'w')
    json.dump(objeto_json, arquivo_new, ensure_ascii=False, indent=4)
    arquivo_new.close()

I think I would have a more platonic way of solving this, for example instead of instantiating the already saved item in the file and recording everything again with the new items, just save the new ones.

Browser other questions tagged

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