2024-05-02|閱讀時間 ‧ 約 23 分鐘

[Python基礎]ini檔案讀取與寫入

INI 檔案是一種配置檔案格式,常用於保存設定資料和組態資訊。

它使用簡單的鍵值對結構來組織資料,通常用於程式、應用程式或操作系統中的配置和初始化設定。

INI 檔案每個鍵值對包含一個名稱()和對應的

基本的檔案格式如下:

[Section1]
Key1 = Value1
Key2 = Value2

以下為維基百科上ini檔範例


在 Python 中,您可以使用 ConfigParser 模組來處理 INI 檔案,包括讀取寫入修改配置資訊

程式範例

ini檔案內容

[owner]
name = Crab
age = 18

[database]
server = 192.168.0.1
port = 8080

Python程式

讀取ini

基本步驟都是先創建configparser物件,在readini文件,路徑可以是相對路徑或者是絕對路徑,在從中獲取出值。

import configparser

# 創建 configparser 物件
config = configparser.ConfigParser()

# 讀取配置文件
config.read('ini路徑', encoding='utf-8')

# 獲取 Section1 中的 Key1 和 Key2 的值
value1 = config['owner']['name']
value2 = config['owner']['age']

print(f"name 的值:{value1}")
print(f"age 的值:{value2}")

print(f"name 的格式:{type(value1)}")
print(f"age 的格式:{type(value2)}")

輸出的結果,都是字串的形式

寫入ini

新增Section 和資料有兩種方法,都類似Python字典的形式。

利用with open這個語法,打開了一個文件來寫入配置。

import configparser

# 創建 ConfigParser 物件
config = configparser.ConfigParser()

# 新增 Section 和資料
config['owner'] = {'name': 'Crab', 'age': '18'}

# 另一種新增Section的方法
config['database'] = {}
config['database']['server'] = '192.168.0.1'
config['database']['port'] = '8080'

# 寫入配置到檔案
with open('ini路徑', 'w') as configfile:
config.write(configfile)
print("INI 檔案已經成功寫入。")







分享至
成為作者繼續創作的動力吧!
利用簡單的程式範例,詳細及白話文的方式解釋
© 2024 vocus All rights reserved.