ga('set', 'anonymizeIp', 1);
Categories: CodingPython

[Python] 讀寫ini配置文檔

Share

給予使用者操作之程式時常會配置ini檔案對參數做設定。

本文介紹如何使用python讀寫操作ini檔案。

ini 配置檔

ini 配置文檔格式範例如下:

[section1]
;此行為註解
var1 = 10
var2 = QQQ
var3 = A1B

其中[section]部分命名不可重複,
每個section下可有多個key-value對。
“;” 為註解行。

Configparser

Python3中使用configparser模組來存取ini文檔。
(若是)python2則是Configparser

# python3
import configparser
# python2
import Configparser

在你的python檔案同層目錄新建一個ini檔案。

以下程式碼示範讀取一個叫做test.ini之文檔。該ini內容為上方範例。

import sys
import configparser
import os

def loadINI():
    curpath = os.path.dirname(os.path.realpath(__file__))
    cfgpath = os.path.join(curpath, 'test.ini')
    # 創建對象
    conf = configparser.Configparser()
    # 讀取INI
    conf.read(cfgpath, encoding='utf-8')
    # 取得所有sections
    sections = conf.sections()
    # 取得某section之所有items,返回格式為list
    items = conf.items('section1')
    return ([sections, items])

iniContent = loadINI()
print('Sections= ' + iniContent[0])
print('\nItems= ' + iniContent[1])

input("按下任意鍵結束")

上方輸出結果為如下:

Sections= section1
Items= [(‘var1′, ’10’), (‘var2’, ‘QQQ’), (‘var3’, ‘A1B’)]

進階用法:remove

如果想刪除某section中的某個item(以key辨識)

conf.remove_option('section1', 'var2')

如果想刪除整個section

conf.remove_section('section1')

進階用法:add

添加一個section。

conf.add_section('section2')

在某section中添加items。

conf.set('section2', 'var1', '20')
conf.set('section2', 'var2', 'AAA')

進階用法:write寫入

write寫入分為兩種,一種會刪除原本的文檔內容,重新寫入。

conf.write(open(cfgpath, "w"))

另一種為不刪除原本文檔,直接在原本文檔繼續寫入內容。

conf.write(open(cfgpath, "a"))

write是在前方講到的remove跟add方法後使用,
只有在執行conf.write()方法之後才會實際修改ini文檔內容。

Jys

Published by
Jys

Recent Posts

[python] Flask Create RESTful API

This article gi... Read More

2 年 前發表

[Javascript] 新增/刪除JSON中key值

在web訊息交換常會需要對JS... Read More

2 年 前發表

[JAVA] SQL Server Connection

本文介紹JAVA連線SQL s... Read More

3 年 前發表