RE: Python's ConfigParser

  • From: "Ken Perry" <whistler@xxxxxxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Sat, 27 Jun 2009 11:12:13 -0400

 

 

What you have to do is do a read config then do all the stuff you want and then 
do a write config which yes will over write the file but that won’t matter 
because you have the config that you read.  You can set anything you like in 
the config before you write it and it will have the old settings and the new.

 

So the way you would use it is like this

 

myConf=LoadConfig()

 

#do stuff

 

saveConfig(myConf)

 

Ken  

 

From: programmingblind-bounce@xxxxxxxxxxxxx 
[mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of BlueScale
Sent: Saturday, June 27, 2009 4:12 AM
To: programmingblind@xxxxxxxxxxxxx
Subject: Python's ConfigParser

 

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: