python从文本文件创建列表

时间:2014-12-01 12:48:14

标签: python python-2.7

嗨我有大文本文件,我想在python中读取文件并将数据保存在列表中。 文件的结构就像这样

[{"address":"office1","id":"3311"},{"address":"office2","id":"3322"}]
[{"address":"office3","id":"3312"},{"address":"office4","id":"3323"}]

我想将第一行保存在一个列表中,将第二行保存在不同列表中。能否解释一下如何做到这一点。

1 个答案:

答案 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'}]]