代码之家  ›  专栏  ›  技术社区  ›  thinwybk

我只能通过Python2配置解析器写注释吗[[副本]

  •  0
  • thinwybk  · 技术社区  · 7 年前

    如何将注释写入节中的给定文件?

    import ConfigParser
    with open('./config.ini', 'w') as f:
        conf = ConfigParser.ConfigParser()
        conf.set('DEFAULT', 'test', 1)
        conf.write(f)
    

    [DEFAULT]
    test = 1
    

    但是我怎样才能得到一个里面有注释的文件呢 [DEFAULT] 部分,如:

    [DEFAULT]
    ; test comment
    test = 1
    

    我知道我可以通过以下方式将代码写入文件:

    import ConfigParser
    with open('./config.ini', 'w') as f:
        conf = ConfigParser.ConfigParser()
        conf.set('DEFAULT', 'test', 1)
        conf.write(f)
        f.write('; test comment') # but this gets printed after the section key-value pairs
    

    0 回复  |  直到 11 年前
        1
  •  34
  •   Eric O. Lebigot    9 年前

    如果版本为>=2.7

    此代码段:

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

    将创建如下ini文件:

    [default_settings]
    ; comment here
    test = 1
    
        2
  •  7
  •   dsanchez    7 年前

    更新3.7

    例1:

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

    例2:

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

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

    其中“SECTION”是要添加注释的区分大小写的节名称。使用“None”(无引号)而不是空字符串('')将允许您设置注释而不留下尾随“=”。

        3
  •  5
  •   Marat Zaynutdinoff    15 年前

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

    已创建conf文件

        [default_settings]
        ; comment here = 
        test = 1
    

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

    给予

    [('test','1')]
    
        4
  •  4
  •   fwilhelm    8 年前

    ConfigUpdater . 它有许多更方便的选项来以一种微创的方式更新配置文件。

    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)
    
    推荐文章