ConfigParser : overwrite ?

cantabile cantabile.03 at wanadoo.fr
Sun Jul 17 13:43:46 EDT 2005


Robert Kern a écrit :
> cantabile wrote:
> 
>> Hi, I'm trying and updating an .ini file with ConfigParser but each time
>> I call 'write', it appends the whole options another time to the file.
>> For example :
>> Here's the inital ini file
>>
>> [section1]
>> foodir: %(dir)s/whatever
>> dir: foo
>>
>> Here's my code :
>> filename = ...
>> config = ConfigParser.ConfigParser()
>> config.read(filename)
>> config.set('section1', 'dir', 'anotherdir')
>> f = open(filename, 'r+')
>> config.write(f)
>> f.close()
>>
>> Then I get :
>>
>> [section1]
>> foodir: %(dir)s/whatever
>> dir: anotherdir
>>
>> [section1]
>> foodir: %(dir)s/whatever
>> dir: foo
>>
>> I tried also with 'w', 'w+', 'a' ...
> 
> 
> Are you sure you tried it with 'w' as the mode?
> 
> In [1]: !cat foo.ini
> [section1]
> foodir: %(dir)s/whatever
> dir: foo
> In [2]: fn = 'foo.ini'
> 
> In [3]: import ConfigParser
> 
> In [4]: cfg = ConfigParser.ConfigParser()
> 
> In [5]: cfg.read(fn)
> Out[5]: ['foo.ini']
> 
> In [6]: cfg.set('section1', 'dir', 'anotherdir')
> 
> In [7]: f = open(fn, 'w')
> 
> In [8]: cfg.write(f)
> 
> In [9]: f.close()
> 
> In [10]: !cat foo.ini
> [section1]
> foodir = %(dir)s/whatever
> dir = anotherdir
> 
You are right, it works.
I thought I had tried it ...
Thanks. :)



More information about the Python-list mailing list