1. 程式人生 > >統計系列之配置檔案的解析

統計系列之配置檔案的解析

運用讀取資料庫的配置檔案為例子:

1.首先來看一下配置檔案的格式:


[rds_mysql]
ip=localhost
port=3306
db=test1,test2
user=root
passwd=123456
enable=1

2.利用configparser讀取配置檔案:

#建立物件
conf = ConfigParser.ConfigParser()
#獲取當前檔案所在的資料夾的路徑,如果配置檔案沒有和當前檔案放在同一個資料夾下,此處應為配置檔案的路徑
path = os.path.dirname(os.path.realpath(__file__)) + '/'
#讀取配置檔案,檔名為xxx.ini
conf.read(path + 'xxx.ini')

3.解析配置檔案:

    read_DB = {
        'host': conf.get("rds_mysql", "ip"),
        'username': conf.get("rds_mysql", "user"),
        'password': conf.get("rds_mysql", "passwd"),
        'port': conf.get("rds_mysql", "port"),
        'database':"test1",
    }