Python 寫入 ini 設定檔 ConfigParser 用法教學

本篇介紹如何在 Python 寫入 ini 設定檔,在上一篇我們已經學習過Python 怎麼讀取 ini 檔,這篇我們就來講講怎麼用內建的 configparser 模組來寫入 .ini 設定檔。

Python 寫入 ini 設定檔

在 python 中我們想要將一些程式執行過程中的一些設定檔給儲存下來以便下次利用時,我們可以使用 ini 設定檔來儲存,

以下這個範例是示範將 host 與 port 給寫入到 ini 檔,而且他們兩個都是在http 這個 section 之下,當然你也可以建立很多個 section下面存放各種資料,這邊只先示範一個 section 的範例,

python3-ini-write.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import configparser

host = 'https://www.google.com'
port = 80

config = configparser.ConfigParser()
config['http'] = {}
config['http']['host'] = host
config['http']['port'] = str(port)

with open('config.ini', 'w') as f:
config.write(f)

程式執行完後就可以看見目錄下會輸出一個 config.ini 的檔案,內容如下,

config.ini
1
2
3
[http]
host = https://www.google.com
port = 80

以上就是 Python 寫入 ini 設定檔的方法,

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python 讀取 ini 設定檔 ConfigParser 用法教學
Python 讀取 txt 文字檔
Python 讀取 csv 檔案
Python 寫入 csv 檔案
Python str 字串用法與範例
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 讓程式 sleep 延遲暫停時間
Python 產生 random 隨機不重複的數字 list
Python PyAutoGUI 使用教學
Python OpenCV resize 圖片縮放