开发者

Updating section in ConfigParser (or an alternative)

开发者 https://www.devze.com 2022-12-24 20:26 出处:网络
I am making a plugin for another program and so I am trying to make thing as lightweight as possible.

I am making a plugin for another program and so I am trying to make thing as lightweight as possible.

What i need to do is be able to update the name of a section in the ConfigParser's config file.

[project name]
author:john doe
email: spam@example.com
year: 2010

I then have text fields where user can edit project's name, author, email and year.

I don't think changing [project name] is possible, so I have thought of two solutions:

1 -Have my config file like this:

[0]
projectname: foobar
author:john doe
email: spam@example.com
year: 2010

that way i can change project's name just like another option. But the problem is, i would need the section # to be auto incremented ([0], [1], etc). And to do this i would have to get every se开发者_运维技巧ction, sort of, and figure out what the next number should be.

The other option would be to delete the entire section and its value, and re-add it with the updated values which would require a little more work as well, such as passing a variable that holds the old section name through functions, etc, but i wouldn't mind if it's faster.

Which of the two is best? or is there another way? I am willing to go with the fastest/lightweight solution possible, doesn't matter if it requires more work or not.


ini files are probably best suited for configuring applications, with well-defined inputs and so forth. It sounds like you want a more generic serialization tool; JSON would probably work well for this. Perhaps you want to store a JSON representation of a list (hence your incrementing indices) of dicts with those fields?

The usage of the json module in the stdlib is pretty simple. For example, to store a couple records you would

import json

projects = []
projects.append({'project_name': 'foobar', 
                 'author': 'John Doe', 
                 'email': 'spam@example.com', 
                 'year': '2010'})
projects.append({'project_name': 'baz', 
                 'author': 'Cat Stevens', 
                 'email': 'cs@example.com', 
                 'year': '2009'})

with open('projects.json', 'w') as f:
    json.dump(projects, f)

Similarly you would recover the serialized data from the file with json.load(f), where you have opened f in read mode.

0

精彩评论

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