更新INI文件而不删除注释

问题描述 投票:16回答:3

考虑以下INI文件:

[TestSettings]
# First comment goes here
environment = test

[Browser]
# Second comment goes here
browser = chrome
chromedriver = default

...

我正在使用Python 2.7来更新ini文件:

config = ConfigParser.ConfigParser()
config.read(path_to_ini)
config.set('TestSettings','environment',r'some_other_value')

with open(path_to_ini, 'wb') as configfile:
    config.write(configfile)

如何在不删除注释的情况下更新INI文件。 INI文件已更新,但注释已删除。

[TestSettings]
environment = some_other_value

[Browser]
browser = chrome
chromedriver = default
python ini configparser
3个回答
8
投票

ConfigObj在阅读和编写INI文件时保留comments,并且似乎做你想要的。您描述的方案的示例用法:

from configobj import ConfigObj

config = ConfigObj(path_to_ini)
config['TestSettings']['environment'] = 'some_other_value'
config.write()

6
投票

回写时擦除配置文件中的注释的原因是write方法根本没有处理注释。它只是写入键/值对。

绕过这个的最简单方法是使用自定义注释前缀和allow_no_value = True初始化configparser对象。如果我们想保留默认的“#”和“;”在文件中注释行,我们可以使用comment_prefixes ='/'。

即,为了保持评论,你必须欺骗configparser相信这不是评论,这一行是一个没有价值的关键。有趣:)

# set comment_prefixes to a string which you will not use in the config file
config = configparser.ConfigParser(comment_prefixes='/', allow_no_value=True)
config.read_file(open('example.ini'))
...
config.write(open('example.ini', 'w'))

0
投票

ConfigObj几乎是所有情况下的最佳选择。

然而,它不支持没有三重引号的多行值,如ConfigParser do。在这种情况下,一个可行的选择可以是iniparse

例如:

[TestSettings]
# First comment goes here
multiline_option = [
        first line,
        second line,
    ]

您可以通过这种方式更新多行值。

import iniparse
import sys

c = iniparse.ConfigParser()
c.read('config.ini')
value = """[
    still the first line,
    still the second line,
]
"""
c.set('TestSettings', 'multiline_option', value=value)
c.write(sys.stdout)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.