RE: Python's ConfigParser
- From: BlueScale <bluescale1976@xxxxxxx>
- To: programmingblind@xxxxxxxxxxxxx
- Date: Sat, 27 Jun 2009 12:38:56 -0400
Thanks! It works like a charm now, just needed a simple if statement.
I'm actually quite proud of those two functions, now I don't have to
remember and do all of that ConfigParser stuff every time.
Just in case anyone is interested, here's the revised version of
writeVar:
def writeVar(fileName, sectionName, sectionKey, sectionValue):
import ConfigParser
import os
config = ConfigParser.ConfigParser()
if os.path.exists(fileName):
config.read(fileName)
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()
On Sat, 2009-06-27 at 11:12 -0400, Ken Perry wrote:
>
>
>
>
> 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: