4

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

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

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

4

2 回答 2

11

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

文档提到

在 Python 3.0 中,ConfigParser 模块已重命名为 configparser。将源转换为 3.0 时,2to3 工具将自动调整导入。

于 2010-09-16T06:17:18.550 回答