Export a dictionary to .txt file

0

Hello.

I'd like to know how I can export a dict to a .txt file.

and how to import the data that is in the .txt file into the dictionary in the program. When I import, the dictionary gets all bugged, how do I import it correctly?

    
asked by anonymous 28.09.2018 / 04:17

1 answer

4

If you are working only with the default language data types, ie "int", "float", "str" and "bool" you can export and import the dictionary as a JSON file:

#!/usr/bin/env python
from __future__ import print_function
import json

dicionario = {
    'nome': 'Fulano de Tal',
    'idade': 30,
    'saldo': 520.37,
    'online': True,
}

open('dicionario.json','w').write(json.dumps(dicionario))

with open('dicionario.json', 'r') as file_json:
    dicionario_2 = json.loads(file_json.read())

print(dicionario_2)

However, if you have other data types you can use pickle .

#!/usr/bin/env python
from __future__ import print_function
import pickle
from datetime import datetime

dicionario = {
    'nome': 'Fulano de Tal',
    'online': False,
    'ultimo_login': datetime.now()
}

open('dicionario.pickle','w').write(pickle.dumps(dicionario))

with open('dicionario.pickle', 'r') as file_pickle:
    dicionario_2 = pickle.loads(file_pickle.read())

print(dicionario_2)
    
28.09.2018 / 04:53