嗨我有大文本文件,我想在python中读取文件并将数据保存在列表中。 文件的结构就像这样
[{"address":"office1","id":"3311"},{"address":"office2","id":"3322"}]
[{"address":"office3","id":"3312"},{"address":"office4","id":"3323"}]
我想将第一行保存在一个列表中,将第二行保存在不同列表中。能否解释一下如何做到这一点。
答案 0 :(得分:1)
<强> file.txt的强>
[{"address":"office1","id":"3311"},{"address":"office2","id":"3322"}]
[{"address":"office3","id":"3312"},{"address":"office4","id":"3323"}]
<强>码强>
import ast
lists = []
for line in open('file.txt'):
lists.append(ast.literal_eval(line.strip()))
>>> lists
[[{'id': '3311', 'address': 'office1'}, {'id': '3322', 'address': 'office2'}], [{'id': '3312', 'address': 'office3'}, {'id': '3323', 'address': 'office4'}]]