我有一个包含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('},{')
,但是您遇到了明显的问题:它会破坏字典。
答案 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'}]