4
2

More than 3 years have passed since last update.

Python用の設定ファイルを書くときのメモメモ:configparser

Last updated at Posted at 2019-12-03

最近Laravel vuejsにハマってます。Pythonも書いてますが、ちょっと減り気味。
携わってたサービスが少し前に進みそうで嬉しい。

なんか良くこれ彷徨う気がするので自分用のメモ。
なんかiniファイルとか読み込むときの簡易サンプルである。

これいいね。これが欲しかった。ってか何でライブラリで機能提供されてないの。
https://qiita.com/suto3/items/db6f05f943cc2ea2ef59

#!/usr/bin/env python                                                                                                                                         
# -*- coding:utf-8 -*-                                                                                                                                        
import os
import configparser

config = configparser.SafeConfigParser()
#絶対パス使え。(たぶん)
path = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(path, 'hoge.ini')

print(path)
config.read(path)

value = config.get('general', 'hoge1')
print(value)

#======

def get_config(ini):
    for section in ini.sections():
        keys, values = get_section(ini, section)
    return keys, values

def get_section(ini, section):
    keys, values = [], []
    for key in ini.options(section):
        key, value = get_by_key(ini, section, key)
        keys.append(key)
        values.append(value)
    return keys, values

def get_by_key(ini, section, key):
    return [key, ini.get(section, key)]

keys, values = get_config(config)
print(keys, values)



hoge.ini
[general]
name1=名前だよ
path=/home/user/hoge/
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2