[英]How to read a list of dicts from a txt file?
我想阅读这个 txt 文件并在 python 中获取字典列表:
数据.txt:
[{"name": "Aaron", "age": "1"}, {"name": "Bruce", "age": "2"}]
然而:
with open('data.txt','r') as f:
list_of_dict = f.read()
print(list_of_dict[0])
打印--> {"name": "Aaron", "age": "1"}
print(list_of_dict[1])
打印--> {"name": "Bruce", "age": "2"}
print(type(list_of_dict[1])
打印-> dict
print(type(list_of_dict)
打印--> 列表
谢谢
尝试使用json
模块:
import json
with open("data.txt", "r") as f_in:
list_of_dict = json.load(f_in)
print(list_of_dict[0])
print(list_of_dict[1])
print(type(list_of_dict[1]))
print(type(list_of_dict))
印刷:
{'name': 'Aaron', 'age': '1'}
{'name': 'Bruce', 'age': '2'}
<class 'dict'>
<class 'list'>
使用json.load(file)
而不是file.read()
import json
with open("a.txt", encoding="UTF8") as f:
a = json.load(f)
print(type(a)) # <class 'list'>
print(a[0])
print(a[1])
文档: https ://docs.python.org/3/library/json.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.