开发者

Python: Access a dictionary that is located inside of a text file

开发者 https://www.devze.com 2023-03-19 23:53 出处:网络
I am working on a quick and dirty script to get Chromium\'s bookmarks and turn them into a p开发者_开发问答ipe menu for Openbox. Chromium stores it\'s bookmarks in a file called Bookmarks that stores

I am working on a quick and dirty script to get Chromium's bookmarks and turn them into a p开发者_开发问答ipe menu for Openbox. Chromium stores it's bookmarks in a file called Bookmarks that stores information in a dictionary form like this:

{
   "checksum": "99999999999999999999",
   "roots": {
      "bookmark_bar": {
         "children": [ {
            "date_added": "9999999999999999999",
            "id": "9",
            "name": "Facebook",
            "type": "url",
            "url": "http://www.facebook.com/"
         }, {
            "date_added": "999999999999",
            "id": "9",
            "name": "Twitter",
            "type": "url",
            "url": "http://twitter.com/"

How would I open this dictionary in this file in Python and assign it to a variable. I know you open a file with open(), but I don't really know where to go from there. In the end, I want to be able to access the info in the dictionary from a variable like this bookmarks[bookmarks_bar][children][0][name] and have it return 'Facebook'


Do you know if this is a json file? If so, python provides a json library.

Json can be used as a data serialization/interchange format. It's nice because it's cross platform. Importing this like you ask seems fairly easy, an example from the docs:

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

So in your case it would look something like:

import json
with open(file.txt) as f:
    text = f.read()
    bookmarks = json.loads(text)
print bookmarks[bookmarks_bar][children][0][name]


JSON is definitely the "right" way to do this, but for a quick-and-dirty script eval() might suffice:

with open('file.txt') as f:
    bookmarks = eval(f.read())
0

精彩评论

暂无评论...
验证码 换一张
取 消