2

我需要一些(基本)python代码的帮助:

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")

我要做的是从 .ini 文件(与脚本共享相同的名称)中读取它,如果它不存在则创建它。

同样,如果它不存在,它将读取该部分并创建它。它正在读取的选项相同,如果不存在,请将选项设置为默认值。

照原样,它会创建文件,但它是空的,因此它不会读取任何内容,也不会破坏 while 循环。

我对 python 很陌生,从未使用过 ConfigParser 模块,这可能是我被卡住的原因(或者因为我遗漏了一些明显的东西)

无论哪种方式,我都会感谢任何帮助。

4

1 回答 1

4

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.

于 2012-12-13T19:29:00.157 回答