关于python:更新INI文件而不删除注释

Update INI file without removing comments

考虑以下INI文件:

1
2
3
4
5
6
7
8
9
10
[TestSettings]
# First comment goes here
environment = test

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

...

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

1
2
3
4
5
6
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文件已更新,但注释已删除。

1
2
3
4
5
6
[TestSettings]
environment = some_other_value

[Browser]
browser = chrome
chromedriver = default


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

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

即,要保留注释,您必须欺骗configparser使其认为这不是注释,该行是没有值的键。有趣的:)

1
2
3
4
5
# 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'))


ConfigObj在读取和写入INI文件时保留注释,并且似乎可以满足您的要求。您描述的场景的用法示例:

1
2
3
4
5
from configobj import ConfigObj

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


几乎在所有情况下,ConfigObj都是最佳选择。

但是,它不支持没有三引号的多行值,就像ConfigParser一样。在这种情况下,可行的选择可能是无用的。

例如:

1
2
3
4
5
6
[TestSettings]
# First comment goes here
multiline_option = [
        first line,
        second line,
    ]

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

1
2
3
4
5
6
7
8
9
10
11
12
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)