I saved some dictionaries in a.txt with:
# The form of store the data is in a dictionary of a dictionary
data = { "DNI": dni, "Nombre": name, "Apellido": surname, "Usuario": username, "Contraseña": password}
with open(dbUsers, "a+") as db:
db.write("\n" + str(data))
# Finally the program send a OK message and close the file
db.close()
print("El usuario y sus datos se han introducido correctamente.")
Now I'm trying to get the different lines (one line, one dictionary) of the .txt
with:
with open(dbUsers, "r") as db:
for line in db:
But that lines are not a dictionary so I can't get the different values with the keys. My question is: how can I convert the different lines (with a dictionary format) with a dictionary inside in python?
You can use ast.literal_eval
to convert the string to a dict.
import ast
with open(dbUsers, "r") as db:
for line in db:
if not line.isspace():
d = ast.literal_eval(line)
print(d)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.