ConfigParser : overwrite ?
Robert Kern
rkern at ucsd.edu
Sun Jul 17 12:12:33 EDT 2005
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
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list