简体   繁体   中英

how do I import an array containing dictionary from a text file?

I have a text file with cookies inside. It looks like this:

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

I store it into a string variable like this:

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

I am not able to transform it into an array with each elements as dictionary. I have tried cookie2 = cookie.split(',') and cookie2 = cookie.split('},{') but you get the obvious issue: it breaks dictionaries.

Since your input seems formatted as JSON, look into the json module. It will do the parsing for you: https://docs.python.org/3.4/library/json.html

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

That looks like json data, you can use json module to parse it. Something like -

import json
with open('<filename>') as f:
    data = json.load(f)

Demo -

file -

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

Code -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM