如何使Configparser在.ini文件中的更改持久化

-2 投票
1 回答
1640 浏览
提问于 2025-04-17 18:16

如何修改.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

试试使用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)

撰写回答