Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Write Dictionary Contents to ConfigParser

I am trying to write (and later read into) the contents of a dictionary to ConfigParser, and I believe I am doing it correctly according to the docs , but cannot seem to get it to work. Can someone assist?

import ConfigParser
parser = ConfigParser.ConfigParser()

parser['User_Info'] = {"User1-votes":"36","User1-gamestart":"13232323","User2-votes":"36","User2-gamestart":"234234234","User3-votes":"36","User3-gamestart":"13232323"}

Traceback (most recent call last):   File "<stdin>", line 1, in
<module> AttributeError: ConfigParser instance has no attribute '__setitem__'

What I am looking for is to have a dictionary that I can update, and at the end write to a config file so it would look like:

[User_Info]
User1-gamestart = 13232323
User3-votes = 36
User2-votes = 36
User1-votes = 36
User2-gamestart = 234234234
User3-gamestart = 13232323
like image 937
Bill Swearingen Avatar asked Apr 09 '13 18:04

Bill Swearingen


1 Answers

You are reading the documentation for python 3.4, but you are probably using an older version of python.

Here is how to use ConfigParser in older versions of python:

import ConfigParser
parser = ConfigParser.ConfigParser()

info = {"User1-votes":"36","User1-gamestart":"13232323","User2-votes":"36","User2-gamestart":"234234234","User3-votes":"36","User3-gamestart":"13232323"}

parser.add_section('User-Info')
for key in info.keys():
    parser.set('User-Info', key, info[key])

with open('config.ini', 'w') as f:
    parser.write(f)
like image 176
Ionut Hulub Avatar answered Oct 20 '22 09:10

Ionut Hulub