how to write file with configparser

Robert Amesz rcameszREMOVETHIS at dds.removethistoo.nl
Sat Apr 21 17:41:34 EDT 2001


hlt2000 at hotmail.com wrote:

> I,m using the ConfigParser module to read my ini file. After my
> program has ran I want to update the ini file. With configdict.set I
> modify an option to a new value. 
> 
> How do I write this back onto my file system?  
> 
> cfgfile=open('config.ini',' rw')
> ...
> cfgdict.set(....)
> ...
> cfgdict.write(cfgfile)
> 
> This gives an IOerror: (0,Error)
> 
> What is the right way to do this?

It is imperative that you open the file the right way, the mode must be 
either 'w' or 'w+'. If you use 'r+' the file isn't trunctated, and junk 
could be left at the end of the file. (It might be some time before a 
bug like that manifests itself.)

Also note there's no mode called ' rw' (sic). There isn't even a mode 
called 'rw': There's 'r', 'w' and 'a'. You can add a '+' and/or a 'b' 
to that, but that's it.

The configparser is nice, but the write-method needs a bit of an 
overhaul. It really should accept a filename as a parameter to be 
consistent *and* avoid errors like the one above

Furthermore, it should preserve as much of the original formatting of 
the file as possible, including things like comments and the order of 
the sections and options. In its present form it is inconvenient for 
files which are hand-edited as well as machine-updated.


Robert Amesz



More information about the Python-list mailing list