Python - 读取和/或写入ini文件的选项

时间:2012-12-13 19:08:17

标签: python options ini configparser defaults

我需要一些(基本的)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文件中读取(与脚本共享相同的名称),如果它不存在则创建它。

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

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

我对python很新,并且从未使用过ConfigParser模块,这可能就是为什么我被卡住了(或者因为我错过了一些明显的东西)

无论哪种方式,我都很感激给予任何帮助。

1 个答案:

答案 0 :(得分:4)

你实际上从未写过配置文件。请查看http://docs.python.org/3/library/configparser.html#examples了解一些使用模式。

相关问题