代码之家  ›  专栏  ›  技术社区  ›  Mridang Agarwalla

使用configparser存储和检索元组列表

  •  0
  • Mridang Agarwalla  · 技术社区  · 14 年前

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

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

    是否可以使用configparser模块将其读取到元组列表中?如果没有,我应该使用什么?

    2 回复  |  直到 14 年前
        1
  •  10
  •   Manoj Govindan    14 年前

    , : = 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
  •  2
  •   mechanical_meat nazca    14 年前
    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