pipehappy wrote: > Hello everyone: > > I came across the module ConfigParser and can use it correctly. > > import ConfigParser > fp = open('test.cfg','w+') > config = ConfigParser.ConfigParser() > config.readfp(fp) > config.add_section('test') > config.set('test', 'haha', 'hehe') > print config.sections() > config.write(fp) > > ['test'] > Traceback (most recent call last): > File "configparser.py", line 8, in ? > config.write(fp) > File "C:\Python24\lib\ConfigParser.py", line 369, in write > fp.write("[%s]\n" % section) > IOError: (0, 'Error') > > I trace into the module and when executing the line "fp.write("[%s]\n" > % section)", I find every parameter is correct: fp is still a open file > object and section is 'test', I may miss something, but I just cannot > figure it out. Can someone tell me what's going wrong here? > What is the exact intent of your code? Note that the "w+" mode is documented as truncating the file, which means that your starting configuration will always be null. My first thoughts were therefore related to file position,
For what it's worth, however, note that on my system (Cygwin 2.4.3) this code only breaks the *second* time: >>> import ConfigParser >>> fp = open('test.cfg','w+') >>> config = ConfigParser.ConfigParser() >>> config.readfp(fp) >>> config.add_section('test') >>> config.set('test', 'haha', 'hehe') >>> print config.sections() ['test'] >>> config.write(fp) >>> ### should really have closed fp here? >>> import ConfigParser >>> fp = open('test.cfg','w+') >>> config = ConfigParser.ConfigParser() >>> config.readfp(fp) >>> config.add_section('test') Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.4/ConfigParser.py", line 226, in add_section raise DuplicateSectionError(section) ConfigParser.DuplicateSectionError: Section 'test' already exists >>> config.set('test', 'haha', 'hehe') >>> print config.sections() ['test'] >>> config.write(fp) >>> >>> Adding a seel to the start of the file before the failing statement seems to fix the problem, so I guess my conjecture was right. Try import ConfigParser fp = open('test.cfg','w+') config = ConfigParser.ConfigParser() config.readfp(fp) config.add_section('test') config.set('test', 'haha', 'hehe') print config.sections() fp.seek(0) config.write(fp) fp.close() But then fix that "w+" if this is more than just a test app! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list