Writing comments to files with ConfigParser

后端 未结 4 1320
感动是毒
感动是毒 2020-12-30 19:26

How can one write comments to a given file within sections?

If I have:

import ConfigParser
with open(\'./config.ini\', \'w\') as f:
    conf = Config         


        
相关标签:
4条回答
  • 2020-12-30 19:39

    Update for 3.7

    I've been dealing with configparser lately and came across this post. Figured I'd update it with information relevant to 3.7.

    Example 1:

    config = configparser.ConfigParser(allow_no_value=True)
    config.set('SECTION', '; This is a comment.', None)
    

    Example 2:

    config = configparser.ConfigParser(allow_no_value=True)
    config['SECTION'] = {'; This is a comment':None, 'Option':'Value')
    

    Example 3: If you want to keep your letter case unchanged (default is to convert all option:value pairs to lowercase)

    config = configparser.ConfigParser(allow_no_value=True)
    config.optionxform = str
    config.set('SECTION', '; This Comment Will Keep Its Original Case', None)
    

    Where "SECTION" is the case-sensitive section name you want the comment added to. Using "None" (no quotes) instead of an empty string ('') will allow you to set the comment without leaving a trailing "=".

    0 讨论(0)
  • 2020-12-30 19:58

    You could also use ConfigUpdater. It has many more convenience options to update configuration files in a minimal invasive way.

    You would basically do:

    from configupdater import ConfigUpdater
    
    updater = ConfigUpdater()
    updater.add_section('DEFAULT')
    updater.set('DEFAULT', 'test', 1)
    updater['DEFAULT']['test'].add_before.comment('test comment', comment_prefix=';')
    with open('./config.ini', 'w') as f:
        updater.write(f)
    
    0 讨论(0)
  • 2020-12-30 20:01

    You can use the allow_no_value option if you have Version >= 2.7

    This snippet:

    import ConfigParser
    
    config = ConfigParser.ConfigParser(allow_no_value=True)
    config.add_section('default_settings')
    config.set('default_settings', '; comment here')
    config.set('default_settings', 'test', 1)
    with open('config.ini', 'w') as fp:
        config.write(fp)
    
    
    config = ConfigParser.ConfigParser(allow_no_value=True)
    config.read('config.ini')
    print config.items('default_settings')
    

    will create an ini file like this:

    [default_settings]
    ; comment here
    test = 1
    
    0 讨论(0)
  • 2020-12-30 20:03

    You can create variable that starts by # or ; character:

    conf.set('default_settings', '; comment here', '')
    conf.set('default_settings', 'test', 1)
    

    created conf file is

        [default_settings]
        ; comment here = 
        test = 1
    

    ConfigParser.read function won't parse first value

    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    print config.items('default_settings')
    

    gives

    [('test','1')]
    
    0 讨论(0)
提交回复
热议问题