【发布时间】:2010-09-16 06:02:41
【问题描述】:
我想在配置文件中存储一些配置数据。这是一个示例部分:
[URLs]
Google, www.google.com
Hotmail, www.hotmail.com
Yahoo, www.yahoo.com
是否可以使用 ConfigParser 模块将其读入元组列表中?如果没有,我用什么?
【问题讨论】:
标签: python configparser
我想在配置文件中存储一些配置数据。这是一个示例部分:
[URLs]
Google, www.google.com
Hotmail, www.hotmail.com
Yahoo, www.yahoo.com
是否可以使用 ConfigParser 模块将其读入元组列表中?如果没有,我用什么?
【问题讨论】:
标签: python configparser
您能否将分隔符从逗号 (,) 更改为分号 (:) 或使用等号 (=)?在这种情况下,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')]
【讨论】:
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')]
ConfigParser 模块已 在 Python 3.0 中重命名为 configparser。 2to3工具会自动适应 转换源时导入 到 3.0。
【讨论】: