使用ConfigParser模組解析配置檔案

2021-06-29 00:50:31 字數 1554 閱讀 8575

python提供了configparser模組來解析配置檔案,它解析的配置檔案格式類似於ini配置檔案,檔案被分成若干個section,每個section中有具體的配置資訊,例如

[mysqld]

user = mysql

pid-file = /var/run/mysqld/mysqld.pid

skip-external-locking

old_passwords = 1

skip-bdb=true

其中mysqldb就是乙個section,configparser模組需要通過section才能對其中的配置進行插入,更新,刪除等操作。那對於沒有section的配置檔案應該怎麼處理呢,例如配置檔案是這樣的:

user = mysql

pid-file = /var/run/mysqld/mysqld.pid

skip-external-locking

old_passwords = 1

skip-bdb=true

在這裡提供的解決方案是:在處理配置檔案第一行手工加入section標識,在處理完成之後,再將第一行刪除,具體**如下:

def _add_section(self, file_name, section="[default]"):

conf_list = open(file_name).read().split("\n")

conf_list.insert(0, section)

fp = open(file_name, "w")

fp.write("\n".join(conf_list))

fp.close()

def _clear_section(self, file_name):

conf_list = open(file_name).read().split("\n")

conf_list.pop(0)

fp = open(file_name, "w")

fp.write("\n".join(conf_list))

fp.close()

def set_property(self, key, value, file_name):

self._add_section(file_name)

c = configparser.configparser()

c.optionxform = str

c.read(file_name)

c.set("default", key, value)

c.write(open(file_name, "w"))

self._clear_section(file_name)

其中_add_section中增加了section,命名為default,_clear_section刪除了default這個section標識。在set_property就可以呼叫configparser的set方法(或其他方法)對屬性進行操作。

Python中ConfigParser模組的使用

簡略介紹 configparser模組是用來處理配置檔案的。將配置項專門放到乙個配置檔案裡是個好習慣,用configparser模組可以很方便地對配置檔案進行修改。相應的,配置檔案也要遵循乙個標準格式。configparser有read 方法,用於讀取配置檔案,sections 方法,用於獲取所有小...

PyYAML和configparser模組講解

python也可以很容易的處理ymal文件格式,只不過需要安裝乙個模組,參考文件 ymal主要用於配置檔案。configparser模組 用於生成和修改常見配置文件,當前模組的名稱在 python 3.x 版本中變更為 configparser。比如mysql,nginx,php配置檔案都是這種格式...

ConfigParser 模組 使用

可以幫助我們讀取配置資訊的模組 準確說是把一些不想寫死或者不願意公開但要用到的資訊封裝起來使用的模組 使用方法 把資訊先存在ini 檔案中格式如下 ini db db host 127.0.0.1 db port 69 db user root db pass root host port 69 c...