如何使用.ini文件中的Configparser进行更改

时间:2013-03-07 14:39:57

标签: python

如何修改.ini文件?我的ini文件看起来像这样。我希望格式部分ini可以像这样更改[空格要替换为制表符后跟$] 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"

这就是我写的

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

输出就是我想要的。但是当我打开.ini文件时,我看到没有变化吗? 可能是当我再次阅读该部分,它从内存加载?我是如何永久改变的?

1 个答案:

答案 0 :(得分:0)

尝试使用write方法。

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

当您使用config.read('myconfig.ini')读取配置时,您已完全“保存”了该文件。现在你要做的就是修改内容。

# 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)