KnowHow

技術的なメモを中心にまとめます。
検索にて調べることができます。

configparserによる設定ファイルの使い方

登録日 :2024/09/13 05:11
カテゴリ :Python基礎

configファイルをpythonプログラムで読み込むときに便利なconfigparserのサンプル

import configparser


def create_config(file):
    config = configparser.ConfigParser()
    config['DEFAULT'] = {
        'debug': True
    }
    config['web_server'] = {
        'host': '127.0.0.1',
        'port': 80
    }
    config['db_server'] = {
        'host': '127.0.0.1',
        'port': 3306
    }

    with open(file, 'w') as config_file:
        config.write(config_file)


if __name__ == '__main__':
    filename = 'config.ini'
    create_config(filename)

    config = configparser.ConfigParser()
    config.read(filename)
    print(config['web_server'])
    print(config['web_server']['host'])
    print(config['web_server']['port'])
    print(config['db_server']['port'])

config.ini

[DEFAULT]
debug = True

[web_server]
host = 127.0.0.1
port = 80

[db_server]
host = 127.0.0.1
port = 3306