Soullesswaffle Soullesswaffle - 4 years ago 307
Ini Question

Python - Read and/or write options to ini file

i need some help with some (basic) python code:

from ConfigParser import SafeConfigParser
import os
inifile=os.path.basename(__file__)+".ini"

def GetOption(Section, Option, Default):
while True:
parser=SafeConfigParser()
f=open(inifile,"w")
f.close()
parser.read(inifile)
if parser.has_section(Section):
if parser.has_option(Option):
Output=parser.get(Section, Option)
break
else: parser.set(Section, Option, str(Default))
else: parser.add_section(Section)
return Output

Rate=GetOption("MAIN","Rate",0.2208)
Currency=GetOption("MAIN","Currency","euros")


What i'm trying to make it do is read from a .ini file (sharing the same name as the script) and create it if it does not exist.

Likewise, it would then read the Section and create it if it does not exist.
Same for the Option it's reading, and if that does not exist, set the option to Default.

As is, it creates the file, but it is empty and therefore it does not read anything and doesn't break the while loop.

I'm pretty new to python and have never used the ConfigParser module, which may be why i'm stuck (or because i'm missing something blatantly obvious)

Either way, I'd appreciate any help given.

-MickeyXD

Answer Source

You're never actually writing to the config file. Take a look at http://docs.python.org/3/library/configparser.html#examples for some usage patterns.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download