---
# System prepended metadata

title: write .cfg file
tags: [實作相關]

---

write .cfg file
===

sample code

```python=
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 設定檔](https://shengyu7697.github.io/python-write-ini-file/)
[Python内置库：configparser（INI格式配置文件解析）](https://www.cnblogs.com/guyuyun/p/10965125.html)

###### tags: `實作相關`