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')]

ドキュメントには次のことが記載されています

ConfigParser モジュールは、Python 3.0 で configparser に名前が変更されました。2to3 ツールは、ソースを 3.0 に変換するときにインポートを自動的に適応させます。

于 2010-09-16T06:17:18.550 に答える