python操作配置檔案

2021-05-27 00:03:55 字數 1472 閱讀 5427

從配置檔案中讀取程式所需的引數等資訊。步驟:

1、匯入: import configparser

2、開啟配置檔案,配置檔案test.conf要和py檔案在同一目錄下,否則需指定配置檔案所在的目錄:

cf = configparser.configparser() 

cf.read("test.conf")  

3、讀配置檔案資訊

db2_database = cf.get("db2", "database")  

db2_hostname = cf.get("db2", "hostname")  

db2_port     = cf.get("db2", "port")  

db2_protocol = cf.get("db2", "protocol") 

db2_uid      = cf.get("db2", "uid")

db2_pwd      = cf.get("db2", "pwd")

注意:cf.get返回的是字串,如果要返回整型可用sf.getint

完整的指令碼如下

#-*- encoding: utf-8 -*-  

import configparser,string

import ibm_db

# read config file

cf = configparser.configparser()

cf.read("test.conf")

db2_database = cf.get("db2", "database")

db2_hostname = cf.get("db2", "hostname")

db2_port = cf.get("db2", "port")

db2_protocol = cf.get("db2", "protocol")

db2_uid = cf.get("db2", "uid")

db2_pwd = cf.get("db2", "pwd")

配置檔案格式如下

[db2]  

database=dbname

hostname=hostname

port=50000

protocol=tcpip

uid=uid

pwd=pwd

[concurrent]

thread=10

processor=20

python操作配置檔案

coding utf 8 import configparser inifileurl config.ini conf configparser.configparser 生成conf物件 conf.read inifileurl 讀取ini配置檔案 def readconfigfile secti...

python 配置檔案 操作yaml檔案

修改前 chrome path chromedriver.exe jobs a1 uestcedu url 修改後 chrome path chromedriver.exe jobs a1 a2 new uestcedu url usr bin env python coding utf 8 tim...

python操作ini配置檔案

usr bin env python coding utf 8 time 2018 6 22 author liuxuewen site file util ini operation.py software pycharm description ini配置檔案操作工具類 1.讀取.ini配置檔案...