Reputation: 777
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?
Upvotes: 15
Views: 19909
Reputation: 1971
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
Upvotes: 0
Reputation: 1122012
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)
Upvotes: 29