如何从文本文件导入包含字典的数组?

时间:2015-09-27 08:17:45

标签: python arrays python-3.x dictionary

我有一个包含cookie的文本文件。它看起来像这样:

[{"key":"value", "key":"value", "key":"value"},
 {"key":"value", "key":"value", "key":"value"},
 {"key":"value", "key":"value", "key":"value"},
 {"key":"value", "key":"value", "key":"value"}]

我将它存储到这样的字符串变量中:

with open ('example.txt', "r") as myfile:
    cookie = myfile.read().replace('\n', '')

我无法将其转换为数组,每个元素都是字典。 我尝试了cookie2 = cookie.split(',')cookie2 = cookie.split('},{'),但是您遇到了明显的问题:它会破坏字典。

2 个答案:

答案 0 :(得分:3)

由于您的输入似乎格式化为JSON,请查看json模块。它将为您解析:https://docs.python.org/3.4/library/json.html

import json
with open(filename,'r') as f:
    data = json.load(f)

答案 1 :(得分:3)

看起来像json数据,您可以使用json模块来解析它。像 -

这样的东西
import json
with open('<filename>') as f:
    data = json.load(f)

演示 -

档案 -

[{"key1":"value", "key2":"value", "key3":"value"},{"key1":"value", 
"key2":"value", "key3":"value"},{"key1":"value", "key2":"value", 
"key3":"value"},{"key1":"value", "key2":"value", "key3":"value"}]

代码 -

>>> import json
>>> with open('a.txt','r') as f:
...     pprint.pprint(json.load(f))
...
[{'key1': 'value', 'key2': 'value', 'key3': 'value'},
 {'key1': 'value', 'key2': 'value', 'key3': 'value'},
 {'key1': 'value', 'key2': 'value', 'key3': 'value'},
 {'key1': 'value', 'key2': 'value', 'key3': 'value'}]