gpt4 book ai didi

python - 更新 INI 文件而不删除注释

转载 作者:IT老高 更新时间:2023-10-28 21:03:48 24 4
gpt4 key购买 nike

考虑以下 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

最佳答案

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

绕过这一点的最简单方法是使用自定义注释前缀和 allow_no_value = True 初始化 configparser 对象。那么,如果我们要保留默认的“#”和“;”作为文件中的注释行,我们可以指定另一个注释前缀,例如带有 comment_prefixes='/' 的“/”。您可以阅读this section configparser 文档以获取更多信息。

即,要保留注释,您必须欺骗 configparser 使其相信以“#”开头的行是 not 注释,但它们是没有值的键。有趣:)

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

关于python - 更新 INI 文件而不删除注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21476554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com