[英]Creating a dictionary from a .txt
I have to create a login system for a whole bunch of students, where the data is provided by a text file in the following format: 我必须为整个学生创建一个登录系统,其中数据由文本文件以以下格式提供:
[
{
"clave": "f22LwdI",
"alumno": "SI",
"nombre": "Samuel Riquelme"
},
{
"clave": "KaEEkNjFz",
"alumno": "NO",
"nombre": "Paulina Toro",
}
]
I've tried several text reading functions without success. 我尝试了几种文本阅读功能,但均未成功。 So that's why I decided to bring this here.
这就是为什么我决定将其带到这里的原因。
In this case I need to instantiate 2 different users and read the file in order to make this possible. 在这种情况下,我需要实例化2个不同的用户并读取文件,以实现此目的。
you could try this: 您可以尝试以下方法:
from ast import literal_eval
# or read that string in from the file with something like
# with open('filename.txt', 'r') as file:
# strg = file.read()
strg = '''[ { "clave": "f22LwdI", "alumno": "SI", "nombre": "Samuel Riquelme" },
{ "clave": "KaEEkNjFz", "alumno": "NO", "nombre": "Paulina Toro", } ]'''
lst = literal_eval(strg)
print(lst[0]['clave'])
note that the returned object is a list of dictionaries. 请注意,返回的对象是词典列表。
now that the formatting of your question has been updated: your format is (almost) json; 现在,您问题的格式已更新:您的格式(几乎)是json; if you correct the superfluous comma at the end of the second dictionary you could do this:
如果您在第二本字典的末尾更正了多余的逗号,则可以这样做:
import json
strg = '''[
{
"clave": "f22LwdI",
"alumno": "SI",
"nombre": "Samuel Riquelme"
},
{
"clave": "KaEEkNjFz",
"alumno": "NO",
"nombre": "Paulina Toro"
}
]'''
lst = json.loads(strg)
print(lst)
print(lst[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.