【问题标题】:How to make changes using Configparser in .ini file persistent如何在 .ini 文件中使用 Configparser 进行更改持久化
【发布时间】:2013-03-07 14:39:57
【问题描述】:

如何修改.ini文件?我的ini文件看起来像这样。我希望格式部分 ini 像这样更改[空格替换为制表符,后跟 $] Format="[%TimeStamp%] $(%ThreadID%) $ $%_%"

[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 文件时,我在这里看不到任何变化? 可能是当我再次阅读该部分时,它是从内存中加载的吗?我如何使更改永久化

【问题讨论】:

    标签: python


    【解决方案1】:

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

    【讨论】:

    • IOError: [Errno 13] 权限被拒绝。如何解决权限错误。我如何将脚本传递给 sudo 凭据
    • 你需要确保你有写权限,然后才能写入文件。 chmod a+w myconfig.ini 在 unix shell 中将允许任何人写入文件,这样应该可以解决您的问题。或者您可以使用sudo python myscript.py 执行脚本。
    • @Wiliam,如果我更改文件,它的格式就会改变。如何确保 ini 文件格式保持不变。我只需要编辑预先存在的 ini 文件中的一个部分。请指教
    • 当您将 .ini 文件读入 config 对象时,您会将其中的所有内容都保存在文件中。您需要编辑config 对象中的部分,然后使用write 方法将其写回。
    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 2012-12-24
    • 2015-09-06
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多