更新INI文件而不删除注释

sar*_*rbo 18 python ini configparser

考虑以下INI文件:

[TestSettings]
# First comment goes here
environment = test

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

...
Run Code Online (Sandbox Code Playgroud)

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

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

[TestSettings]
environment = some_other_value

[Browser]
browser = chrome
chromedriver = default
Run Code Online (Sandbox Code Playgroud)

小智 9

回写时擦除配置文件中的注释的原因是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'))
Run Code Online (Sandbox Code Playgroud)


Lex*_*ick 8

在读取和写入INI文件时,ConfigObj会保留注释,并且似乎可以执行您想要的操作.您描述的方案的示例用法:

from configobj import ConfigObj

config = ConfigObj(path_to_ini)
config['TestSettings']['environment'] = 'some_other_value'
config.write()
Run Code Online (Sandbox Code Playgroud)

  • `ConfigObj`已经过时了.查看分支https://github.com/DiffSK/configobj (5认同)