python ConfigParser模組介紹

2021-09-25 12:55:25 字數 1833 閱讀 5411

python讀配置檔案的包 configparser

configparser模組在python中用來讀取配置檔案,配置檔案的格式跟windows下的ini配置檔案相似,可以包含乙個或多個節(section), 每個節可以有多個引數(鍵=值)。使用的配置檔案的好處就是不用在程式設計師寫死,可以使程式更靈活。

注意:在python 3 中configparser模組名已更名為configparser

配置檔案 debt_level.conf 如下:

[global]

id=debt_level

name=負債水平相關配置

[debt_monty1]

name=負債金額等級-信用卡

type=segment

lid=9141001003

1=[-inf,0];01級

2=(0,200);02級

3=[200,inf);03級

[debt_monty2]

name=負債金額等級-小貸

type=segment

lid=9141001004

1=[-inf,0];01級

2=(0,200);02級

3=[200,inf);03級

**如下:

import configparser

def read_conf_file(_file):

label_id_dict = {}

config = configparser.configparser()

config.read(_file)

sections = config.sections()

if "global" not in sections:

raise exception('no_global')

global_name = config.get("global", "name")

global_id = config.get("global", "id")

print global_name, global_id

sections.remove("global")

desc_list =

result =

for class_name in sections:

#獲取k,v值 方法1:

#for k in config.options(class_name):

# print k, config.get(class_name, k)

#方法2

for k,v in config.items(class_name):

print k,v

print "*"*30

read_conf_file("debt_level.conf")

執行結果:

負債水平相關配置 debt_level

name 負債金額等級-信用卡

type segment

lid 9141001003

1 [-inf,0];01級

2 (0,200);02級

3 [200,inf);03級

******************************

name 負債金額等級-小貸

type segment

lid 9141001004

1 [-inf,0];01級

2 (0,200);02級

3 [200,inf);03級

******************************

python ConfigParser模組詳解

功能介紹 在程式中使用配置檔案來靈活的配置一些引數是一件很常見的事情,配置檔案的解析並不複雜,在python裡更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是configparser,這裡簡單的做一些介紹。configparser解析的配置檔案的格式比較象ini的配置檔案格式,就是檔案中由多...

python configparser模組用法

配置檔案的資訊 mysqld charater server set utf 8 default engine innodb skip grant table true port 3306 client user root password 123 egon name egon age 18conf...

Python ConfigParser 注意事項

以這個非常簡單的典型配置檔案為例 default serveraliveinterval 45 compression yes compressionlevel 9 forwardx11 yes bitbucket.org user hg topsecret.server.com port 5002...