考虑以下INI文件:
[TestSettings] # First comment goes here environment = test [Browser] # Second comment goes here browser = chrome chromedriver = default ...我正在使用Python 2.7更新ini文件:
I'm using Python 2.7 to update the ini file:
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文件已更新,但注释已删除.
How can I update the INI file without removing the comments. The INI file is updated but the comments are removed.
[TestSettings] environment = some_other_value [Browser] browser = chrome chromedriver = default推荐答案
回写时擦除配置文件中的注释的原因是write方法根本不处理注释.它只写键/值对.
The reason that comments in config files are wiped when writing back is that the write method didn't take care of comments at all. It just writes key/value pairs.
最简单的方法是使用自定义注释前缀和allow_no_value = True来初始化configparser对象. 如果我们要保留默认的#"和;"文件中的注释行,我们可以使用comment_prefixes ='/'.
The easiest way to bypass this is to init configparser object with a customized comment prefix and allow_no_value = True. If we want to keep the default "#" and ";" comment lines in the file, we can use comment_prefixes='/'.
即,要保留注释,您必须欺骗configparser使其认为这不是注释,此行是没有值的键.有趣的:)
i.e., to keep comments, you have to trick configparser into believing this is not a comment, this line is a key without a value. Interesting :)
# 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'))