Python's ConfigParser

  • From: BlueScale <bluescale1976@xxxxxxx>
  • To: "programmingblind@xxxxxxxxxxxxx" <programmingblind@xxxxxxxxxxxxx>
  • Date: Sat, 27 Jun 2009 04:12:00 -0400

Hi,
I wrote 2 functions in Python, one of them is to write settings to a
file, and the other is to read them.  The read function works, the write
function doesn't though.  Well, it sort of works, but if I try to add a
setting later, it overwrites the file with the last setting and erases
everything else.  I tried setting the file object to append, and this
does work, but it creates multiple sections with the same name.  Can
someone please tell me where I am going wrong?  Here are both of the
functions:
def writeVar(fileName, sectionName, sectionKey, sectionValue):
 import ConfigParser
 config = ConfigParser.ConfigParser()
 try:
  config.set(sectionName, sectionKey, sectionValue)
 except:
  config.add_section(sectionName)
  config.set(sectionName, sectionKey, sectionValue)
 with open(fileName, "wb") as configFile:
  config.write(configFile)
  configFile.close()

def getVar(fileName, sectionName, sectionKey):
 import ConfigParser
 import os
 config = ConfigParser.ConfigParser()
 if os.path.exists(fileName) == True:
  try:
   config.read(fileName)
   return config.get(sectionName, sectionKey)
  except:
   return ""
 else:
  return ""

Other related posts: