Try   HackMD

write .cfg file

sample code

import configparser import os conf_directory = "conf" config_file_path = os.path.join('.', conf_directory + '/sysConn.cfg').replace('\\', '/') config = configparser.ConfigParser() config.read(config_file_path) # 讀取 # str type, ex: config['sysConn']['conn'] conn = config['sysConn']['conn'] print(conn, type(conn)) # int type, ex: config['sysConn'].getint('conn') conn = config['sysConn'].getint('conn') print(conn, type(conn)) # 寫入 # 寫入時只允許 str type config['sysConn']['conn'] = str(0) # 寫入後再印出驗證是否有正確寫入 new_conn = config['sysConn']['conn'] print(new_conn, type(new_conn)) # 寫入更新檔案 (寫入檔案後實際打開 sysConn.cfg 查看是否被改) with open(config_file_path, 'w') as f: config.write(f)

Ref.

Python 寫入 ini 設定檔
Python内置库:configparser(INI格式配置文件解析)

tags: 實作相關