Writing comments to files with ConfigParser

后端 未结 4 1368
感动是毒
感动是毒 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 "=".

提交回复
热议问题