A little bit about the code; what I’m trying to do is turning a section into a Dict so I can easily manage it.
Of course, because ConfigParser returns everything as a string (most of the time anyway), I have to change it into the desired type. And that’s where my problem starts.
Code
import ConfigParser, pygame
parser = ConfigParser.SafeConfigParser()
class loadfile(object):
def __init__(self, filename):
self.filename = filename
def load(self):
parser.read(self.filename)
for section_name in parser.sections():
vars()[section_name] = {}
for name, value in parser.items(section_name):
if value.isdigit():
value = int(value)
elif value == "None":
value = None
elif value == "True" or value == "False":
value = parser.getboolean( section_name, name )
else:
value = vars()[ parser.get( section_name, name ) ]
vars()[section_name].update( { name : value } )
print vars()[section_name]
def save(self):
pass
loadfile("config.ini").load()
config.ini
[Display]
Width : 800
Height : 600
Depth : 32
Caption : 45
Flags : pygame.RESIZABLE
Icon : None
Mouse : True
FPS : 30
; Key configuration;
[Keys]
Left : pygame/K_LEFT
Right : pygame.K_RIGHT
Jump : pygame.K_UP
Duck : pygame.K_DOWN
Sprint : pygame.K_RSHIFT
Attack_1 : pygame.K_a
Attack_2 : pygame.K_s
Attack_3 : pygame.K_d
gameMenu : pygame.K_ESCAPE
Dialogue : pygame.K_RETURN
Error
Traceback (most recent call last):
File "C:\Users\***\Desktop\config2.py", line 35, in <module>
loadfile("config.ini").load()
File "C:\Users\***\Desktop\config2.py", line 27, in load
value = vars()[ parser.get( section_name, name ) ]
KeyError: 'pygame.RESIZABLE'
The same error occurred before I put the code in it’s own class, if I used import pygame but it mysteriously went away when I used from pygame import *
Here’s some code that I have written for this, it doesn’t use
ConfigParserbut should work.(atleast in your case)
Output (from your config.ini)
Also, if you use the following type of format for ini file(format may not be the right word), it might be easier to work with.
This can be executed(after spliting from ‘—–‘, and removing first line of each of these.([keys],[display])