To store all the obtained data, you can save it in a JSON file - using the package json
from the standard Python library.
JSON files store the data in the form of a dictionary. Therefore, you should initially separate each item within one dict
, as follows:
dados = {
"bruto": bruto, "passageiro": passageiro, "km": km, "autonomia": autonomia,
"valorlitro": valorlitro, "gastogas": gastogas, "porcentagem": porcentagem
}
After that, turn the object into a JSON string - using the function json.dumps
- and save it to a file with the extension .json
, as in the code below:
import json
with open("banco de dados.json", "w") as file:
string_json = json.dumps(dados)
file.write(string_json)
In your case, as you said the data will be stored monthly, create a list for each key. This way, you can always add new data.
The complete code to create the "database" would look like this:
import json
dados = {
"bruto": [bruto,],
"passageiro": [passageiro,],
"km": [km,],
"autonomia": [autonomia,],
"valorlitro": [valorlitro,],
"gastogas": [gastogas,],
"porcentagem": [porcentagem,]
}
with open("database.json", "w") as file:
string_json = json.dumps(dados)
file.write(string_json)
To add new data to the database, just read the JSON file - check first if it exists - and use the function json.loads
to obtain an object dict
string.
After that, add to the list the new values, through the method append
and save the data again by following the above steps. See the example below:
with open("database.json") as file:
string_json = file.read()
dados = json.loads(string_json)
dados["bruto"].append(bruto)
dados["passageiro"].append(passageiro)
# ...
search open function
– Elton Nunes
You want to save the texts that appear in the input (e.g., "What is your total gross gain?") or the answers that will be read to respond to inputs?
– Leila
Leila I want to save the read answers in the input, so I can have something like a monthly database.
– Paulo