【问题标题】:Storing and retrieving a list of Tuples using ConfigParser使用 ConfigParser 存储和检索元组列表
【发布时间】:2010-09-16 06:02:41
【问题描述】:

我想在配置文件中存储一些配置数据。这是一个示例部分:

[URLs]
Google, www.google.com
Hotmail, www.hotmail.com
Yahoo, www.yahoo.com

是否可以使用 ConfigParser 模块将其读入元组列表中?如果没有,我用什么?

【问题讨论】:

    标签: python configparser


    【解决方案1】:

    您能否将分隔符从逗号 (,) 更改为分号 (:) 或使用等号 (=)?在这种情况下,ConfigParser 会自动为您完成。

    例如将逗号更改为等号后,我解析了您的示例数据:

    # urls.cfg
    [URLs]
    Google=www.google.com
    Hotmail=www.hotmail.com
    Yahoo=www.yahoo.com
    
    # Scriptlet
    import ConfigParser
    filepath = '/home/me/urls.cfg'
    
    config = ConfigParser.ConfigParser()
    config.read(filepath)
    
    print config.items('URLs') # Returns a list of tuples.
    # [('hotmail', 'www.hotmail.com'), ('google', 'www.google.com'), ('yahoo', 'www.yahoo.com')]
    

    【讨论】:

      【解决方案2】:
      import ConfigParser
      
      config = ConfigParser.ConfigParser()
      config.add_section('URLs')
      config.set('URLs', 'Google', 'www.google.com')
      config.set('URLs', 'Yahoo', 'www.yahoo.com')
      
      with open('example.cfg', 'wb') as configfile:
          config.write(configfile)
      
      config.read('example.cfg')
      config.items('URLs')
      # [('google', 'www.google.com'), ('yahoo', 'www.yahoo.com')]
      

      The documentation mentions:

      ConfigParser 模块已 在 Python 3.0 中重命名为 configparser。 2to3工具会自动适应 转换源时导入 到 3.0。

      【讨论】:

        猜你喜欢
        • 2015-08-13
        • 1970-01-01
        • 2019-10-06
        • 2015-10-08
        • 2015-03-19
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        • 2012-03-07
        相关资源
        最近更新 更多