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

def GetOption(Section, Option, Default):
while True:
if parser.has_section(Section):
if parser.has_option(Option):
Output=parser.get(Section, Option)
else: parser.set(Section, Option, str(Default))
else: parser.add_section(Section)
return Output


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.


Answer Source

You're never actually writing to the config file. Take a look at for some usage patterns.

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