2024-03-28 08:17:04 发布
网友
我想在配置文件中存储一些配置数据。下面是一个示例部分:
[URLs] Google, www.google.com Hotmail, www.hotmail.com Yahoo, www.yahoo.com
是否可以使用ConfigParser模块将其读入元组列表?如果没有,我用什么?
您可以将分隔符从逗号(,)改为分号(:)还是使用等号(=)?在这种情况下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')]
The documentation mentions:
The ConfigParser module has been renamed to configparser in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
您可以将分隔符从逗号(
,
)改为分号(:
)还是使用等号(=
)?在这种情况下ConfigParser
将自动为您执行此操作。例如,我在将逗号改为等于后分析了您的示例数据:
The documentation mentions:
相关问题 更多 >
编程相关推荐