15

I have an INI file I need to modify using Python. I was looking into the ConfigParser module but am still having trouble. My code goes like this:

config= ConfigParser.RawConfigParser()
config.read('C:\itb\itb\Webcams\AMCap1\amcap.ini')
config.set('Video','Path','C:\itb\itb')

But when looking at the amcap.ini file after running this code, it remains unmodified. Can anyone tell me what I am doing wrong?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kreuzade
  • 757
  • 5
  • 11
  • 22

2 Answers2

29

ConfigParser does not automatically write back to the file on disk. Use the .write() method for that; it takes an open file object as it's argument.

config= ConfigParser.RawConfigParser()
config.read(r'C:\itb\itb\Webcams\AMCap1\amcap.ini')
config.set('Video','Path',r'C:\itb\itb')
with open(r'C:\itb\itb\Webcams\AMCap1\amcap.ini', 'wb') as configfile:
    config.write(configfile)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I tried `config.write('C:\itb\itb\Webcams\AMCap1\amcap.ini')` but get errors. Do I have to open the file as write or append first? – Kreuzade Jul 24 '12 at 19:00
  • 2
    You need an open file object, as shown in my example; it won't work with a filename (a string). – Martijn Pieters Jul 24 '12 at 19:01
  • @MartijnPieters What about when I want to set multiple values (e.g. multiple paths in this example) per an individual config entry? I can put them in a list as the third parameter, but then the config has this list value. Then when I read them back out via ConfigParser(), I get a string containing a list. Parsable, of course, but not ideal http://pastebin.com/kcxjYA6z – Pyderman Feb 17 '16 at 03:03
  • @Pyderman: the 3rd value is converted to a string, always. If you need more complex formats, invent your own (e.g. `', '.join(listobj)` on write, `[item.strip() for item in value.split(',')]` on read if you need to support multiple items) – Martijn Pieters Feb 17 '16 at 10:02
0

You could use python-benedict, it's a dict subclass that provides normalized I/O support for most common formats, including ini.

from benedict import benedict

# path can be a ini string, a filepath or a remote url
path = 'path/to/config.ini'

d = benedict.from_ini(path)

# do stuff with your dict
# ...

# write it back to disk
d.to_ini(filepath=path)

It's well tested and documented, check the README to see all the features:

https://github.com/fabiocaccamo/python-benedict

Install using pip: pip install python-benedict

Note: I am the author of this project

Fabio Caccamo
  • 1,871
  • 19
  • 21