Python 更新INI文件而不删除注释

Python 更新INI文件而不删除注释,python,ini,configparser,Python,Ini,Configparser,考虑以下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.se

考虑以下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
在读取和写入INI文件时保留,并且似乎可以执行您想要的操作。您描述的场景的使用示例:

from configobj import ConfigObj

config = ConfigObj(path_to_ini)
config['TestSettings']['environment'] = 'some_other_value'
config.write()
几乎在所有情况下都是最佳选择

然而,它不支持没有三重引号的多行值,就像ConfigParser一样。在这种情况下,可以选择一个可行的方案

例如:

[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)

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

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

i、 例如,为了保留注释,您必须欺骗configparser使其相信这不是注释,这一行是没有值的键。有趣:)


ConfigUpdater
可以更新
.ini
文件并保留注释:

但我不知道它是否适用于Python2

从:

ConfigParser的主要区别在于:

  • 更新配置文件中的最小侵入性更改
  • 妥善处理意见,

不能使用
ConfigParser
执行此操作。您需要使用其他库。是否尝试了“允许\u无\u值”参数?allow_no_值对过度读取配置没有影响。也就是说,评论不是一开始就被写下来的……你知道怎么做了吗?可能您可以添加解决方案?必须从INI文件切换到XML。
ConfigObj
已过时。首先,这对我不起作用:
cp=ConfigParser.ConfigParser(allow\u no\u value=True,comment\u prefixes='/')类型错误:\uuu init\uuuuu()得到了一个意外的关键字参数“comment\u prefixes”
,可能这只适用于较新版本的ConfigparserOk,所以我只是用python3尝试了一下,它就可以工作了。使用python2时,上面的错误消息将被打印。这对注释行没有帮助,它们仍然被删除。这最终会降低我所有的注释case@eric.frederich这是因为存在到
configparser
的默认转换器。您可以通过执行
config.optionxform=lambda option:option
绕过它。看见
# 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'))