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

时间:2010-09-16 06:02:42

标签: python configparser

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

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

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

2 个答案:

答案 0 :(得分:10)

您可以将分隔符从逗号(,)更改为分号(:)或使用等号(=)符号吗?在这种情况下,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')]

答案 1 :(得分: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。