Created
May 30, 2018 02:42
-
-
Save pythonsuezo/1ce0b99a2f14b71d7544116e9d0dd3f3 to your computer and use it in GitHub Desktop.
configparserの簡単な使い方
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import configparser | |
import os, sys | |
path = os.path.dirname( sys.argv[0] ) | |
INI = path + "/INI.conf" | |
conf = configparser.SafeConfigParser() | |
conf.read(INI) # 設定ファイルの読み込み | |
# デフォルト設定を記述 conf["セクション名"] = {"キー":"値"} | |
conf["DEFAULT"] = {"host":"localhost", | |
"port":"23", | |
"serial":"COM1", | |
"baudrate":"9600", | |
"data_bit":"8", | |
"parity":"No", | |
"stopbit":"1", | |
"flow_ctrl":"No", | |
"timeout":"20"} | |
# 設定にセクションがあるかどうか TrueかFalse | |
print("option" in conf) | |
# 設定に[option]が無い場合空の物を作る | |
if not "option" in conf: | |
conf["option"] = {} | |
# 設定の読出し | |
option = conf["option"] | |
print("[option]の設定内容") | |
for key in option: | |
print( key + " : " + option[key] ) | |
# 設定の書き込み | |
conf["option"]["host"] = "192.168.0.1" # option["host"]でも可 | |
# 設定をファイルに書き出す | |
with open(INI,"w") as configfile: | |
conf.write(configfile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment