-2

How to modify the .ini file? My ini file looks like this. And i want the format section ini to be changed like this[Space to be replaced with a tab followed by $] Format="[%TimeStamp%] $(%ThreadID%) $<%Tag%> $%_%"

[Sink:2]

Destination=TextFile
FileName=/usr/Desktop/A.log
RotationSize=5000000
MaxSize=50000000
MinFreeSpace=10000000
AutoFlush=true
Format="[%TimeStamp%] (%ThreadID%) <%Tag%> %_%"
Filter="%Severity% >= 0"

This is what i wrote

import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('/usr/local/ZA/var/loggingSettings.ini')
format = config.get('Sink:2', 'Format')
tokens = "\t$".join(format.split())
print format
print tokens
config.set('Sink:2', 'Format', tokens)
newformat = config.get('Sink:2', 'Format')
print newformat

And the Output is the exact what i wanted.But when i open the .ini file, i see no changes here? Could be when i reading again the section , its loading from memory? How did i make the changes permanent

1 Answers1

0

Try using the write method.

with open('myconfig.ini', 'w') as f:    
    config.write(f)

When you read in a config with config.read('myconfig.ini') you have "saved" the file exactly as it is. Now what you want to do is modify the contents.

# Get a config object
config = RawConfigParser()
# Read the file 'myconfig.ini'
config.read('myconfig.ini')
# Read the value from section 'Orange', option 'Segue'
someVal = config.get('Orange', 'Segue')
# If the value is 'Sword'...
if someVal == 'Sword':
    # Then we set the value to 'Llama'
    config.set('Orange', 'Segue', 'Llama')
# Rewrite the configuration to the .ini file
with open('myconfig.ini', 'w') as myconfig:
    config.write(myconfig)
William
  • 2,917
  • 5
  • 30
  • 47
  • IOError: [Errno 13] Permission denied. How do i solve the permission error. How i do pass the script the sudo credential – sunshooter Mar 07 '13 at 14:54
  • Well you need to make sure that you have write permissions before you can write to a file. `chmod a+w myconfig.ini` in a unix shell will let anybody write to the file, so that should solve your problem. Or you can probably execute the script with `sudo python myscript.py`. – William Mar 07 '13 at 15:07
  • @Wiliam, if i change the file, its format gets changed. How to i ensure the ini file format remains intact. I need to just edit one of the section in a pre-existing ini file. please advice – sunshooter Mar 07 '13 at 16:46
  • When you read the .ini file into the `config` object, you are saving everything in there as it is in the file. You need to edit the sections in the `config` object and then write it back using the `write` method. – William Mar 07 '13 at 18:25