Python - Read and/or write options to ini file

10,429

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.

Share:
10,429
mickdekkers
Author by

mickdekkers

Updated on June 04, 2022

Comments

  • mickdekkers
    mickdekkers almost 2 years

    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.