【问题标题】:Python 2.7 ConfigParser with no delimiter没有分隔符的 Python 2.7 ConfigParser
【发布时间】:2017-07-26 04:22:07
【问题描述】:

使用Python 2.7.x和ConfigParser,如何生成配置文件如下?

[Section]
key1
key2
key3

【问题讨论】:

    标签: python-2.7 config delimiter ini


    【解决方案1】:

    = 是格式的一部分,因此您不能告诉 configparser 忽略它。

    但是您可以通过传递io.BytesIO() 对象来欺骗作者,并在写入真实文件时去掉空格+等号。

    独立示例:

    import ConfigParser,io
    
    config = ConfigParser.RawConfigParser()
    
    config.add_section('Section')
    for i in range(1,4):
        config.set('Section', 'key{}'.format(i), '')
    
    # Writing our configuration file to 'example.cfg'
    b = io.BytesIO()
    config.write(b)   # write in a fake file
    
    # now write the modified contents to a real file
    with open('output.ini', 'w') as f:
        for l in b.getvalue().splitlines():
            f.write(l.rstrip("= ")+"\n")
    

    【讨论】:

      【解决方案2】:

      请参阅 python 文档。 https://docs.python.org/2/library/configparser.html

      import ConfigParser
      
      config = ConfigParser.RawConfigParser()
      
      
      config.add_section('Section')
      config.set('Section', 'key1', '')
      config.set('Section', 'key2', '')
      config.set('Section', 'key3', '')
      
      # Writing our configuration file to 'example.cfg'
      with open('example.cfg', 'wb') as configfile:
          config.write(configfile)
      

      【讨论】:

      • 它产生以下输出[Section] key1 = key2 = key3 = 无论如何要从中剥离 =
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      相关资源
      最近更新 更多