Export a dictionary to file . txt

Asked

Viewed 836 times

0

Hello.

I would like to know how I export a dictionary to a file. txt.

and how to import the data that is in the.txt file into the dictionary in the program. When I care, the dictionary gets all fucked up, like I care properly?

1 answer

5

If you are working only with the default data types of the language, that is, "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 types of data you can use the 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)
  • You can also use without read(), json.load(file_json), also when writing to the file. https://docs.python.org/3.3/tutorial/inputoutput.html#saving-Structured-data-with-json, https://docs.python.org/3/library/json.html#json.load

Browser other questions tagged

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