Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top