python開發_configparser_解析.ini配置文件工具_完整版_博主推薦


#
#   最近出了一趟差,是從20號去的,今天回來...
#   就把最近學習的python內容給大家分享一下...
#
'''
   在python中,configparser模塊提供了操作*.ini配置文件的一些操作方法
   就如python的API中所描述的一樣:

       This module provides the ConfigParser class which implements
    a basic configuration language which provides a structure similar
    to what’s found in Microsoft Windows INI files. You can use this
    to write Python programs which can be customized by end users easily.

    以下實現的功能是:
    將一些配置信息寫入到指定文件中,並且提供方法獲取配置文件中的信息
'''

下面是我做的demo,

運行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
SHOW_LOG : True
The path [C:\test] dosen't exist!
Created the path [C:\test]
打開文件:[C:\test\hongten.ini]
開始寫入數據:[{'url': 'jdbc:oracle:thin:@', 'ip': '172.0.0.1', 'isJndiDs': 'false', 'user': 'root', 'port': '1521', 'driverClassName': 'oracle.jdbc.OracleDriver', 'password': '*******', 'name': 'hongten_datasource', 'dbName': 'db_hongten'}]
打開文件:[C:\test\hongten.ini]
開始讀取數據:[url] = [jdbc:oracle:thin:@]
開始讀取數據:[ip] = [172.0.0.1]
開始讀取數據:[isjndids] = [false]
開始讀取數據:[user] = [root]
開始讀取數據:[port] = [1521]
開始讀取數據:[driverclassname] = [oracle.jdbc.OracleDriver]
開始讀取數據:[password] = [*******]
開始讀取數據:[name] = [hongten_datasource]
開始讀取數據:[dbname] = [db_hongten]
url : jdbc:oracle:thin:@,ip : 172.0.0.1,isjndids : false,user : root,port : 1521,driverclassname : oracle.jdbc.OracleDriver,password : *******,name : hongten_datasource,dbname : db_hongten
##################################################
打開文件:[C:\test\hongten.ini]
寫入數據:[DATA_SOURCE_INFO]
[url : jdbc:oracle:thin:@,ip : 172.0.0.1,isjndids : false,user : root,port : 1521,driverclassname : oracle.jdbc.OracleDriver,password : *******,name : hongten_datasource,dbname : db_hongten]
寫入數據:[PROVINCES]
[zj : Zhejiang,bj : Beijing,gd : Guangdong,sh : Shanghai]
寫入數據:[AUTHOR_INFO]
[create : 2013-08-22,blog : http://www.cnblogs.com/hongten,author : hongten,mailto : hongtenzone@foxmail.com,qq : 648719819,version : 1.0]
打開文件:[C:\test\hongten.ini]
獲取模塊名稱:[DATA_SOURCE_INFO]
開始讀取數據:[url] = [jdbc:oracle:thin:@]
開始讀取數據:[ip] = [172.0.0.1]
開始讀取數據:[isjndids] = [false]
開始讀取數據:[user] = [root]
開始讀取數據:[port] = [1521]
開始讀取數據:[driverclassname] = [oracle.jdbc.OracleDriver]
開始讀取數據:[password] = [*******]
開始讀取數據:[name] = [hongten_datasource]
開始讀取數據:[dbname] = [db_hongten]
獲取模塊名稱:[PROVINCES]
開始讀取數據:[zj] = [Zhejiang]
開始讀取數據:[bj] = [Beijing]
開始讀取數據:[gd] = [Guangdong]
開始讀取數據:[sh] = [Shanghai]
獲取模塊名稱:[AUTHOR_INFO]
開始讀取數據:[create] = [2013-08-22]
開始讀取數據:[blog] = [http://www.cnblogs.com/hongten]
開始讀取數據:[author] = [hongten]
開始讀取數據:[mailto] = [hongtenzone@foxmail.com]
開始讀取數據:[qq] = [648719819]
開始讀取數據:[version] = [1.0]
{'DATA_SOURCE_INFO': {'driverclassname': 'oracle.jdbc.OracleDriver', 'user': 'root', 'isjndids': 'false', 'name': 'hongten_datasource', 'port': '1521', 'url': 'jdbc:oracle:thin:@', 'password': '*******', 'ip': '172.0.0.1', 'dbname': 'db_hongten'}, 'PROVINCES': {'bj': 'Beijing', 'zj': 'Zhejiang', 'gd': 'Guangdong', 'sh': 'Shanghai'}, 'AUTHOR_INFO': {'create': '2013-08-22', 'blog': 'http://www.cnblogs.com/hongten', 'author': 'hongten', 'mailto': 'hongtenzone@foxmail.com', 'qq': '648719819', 'version': '1.0'}}
##################################################
打開文件:[C:\test\hongten.ini]
獲取到[C:\test\hongten.ini]文件,模塊:[DATA_SOURCE_INFO],鍵:[name],值:[hongten_datasource]
hongten_datasource
>>> 

c:\\test目錄下面的情況:

====================================================

代碼部分:

====================================================

  1 #python configparser
  2 
  3 #Author  : Hongten
  4 #Mailto  : hongtenzone@foxmail.com
  5 #Blog    : http://www.cnblogs.com/hongten
  6 #QQ      : 648719819
  7 #Create  : 2013-08-22
  8 #Version : 1.0
  9 
 10 import os
 11 import configparser
 12 
 13 '''
 14    在python中,configparser模塊提供了操作*.ini配置文件的一些操作方法
 15    就如python的API中所描述的一樣:
 16 
 17        This module provides the ConfigParser class which implements
 18     a basic configuration language which provides a structure similar
 19     to what’s found in Microsoft Windows INI files. You can use this
 20     to write Python programs which can be customized by end users easily.
 21 
 22     以下實現的功能是:
 23     將一些配置信息寫入到指定文件中,並且提供方法獲取配置文件中的信息
 24 '''
 25 
 26 #global var
 27 SHOW_LOG = True
 28 #Microsoft Windows INI files path
 29 HONGTEN_INT_PATH = ''
 30 
 31 def mkdirs(path):
 32     '''創建多級目錄'''
 33     if os.path.exists(path):
 34         if SHOW_LOG:
 35             print('The path [{}] existing!'.format(path))
 36     else:
 37         if SHOW_LOG:
 38             print('The path [{}] dosen\'t exist!'.format(path))
 39         os.makedirs(path)
 40         if SHOW_LOG:
 41             print('Created the path [{}]'.format(path))
 42 
 43 def get_path(absPath):
 44     '''獲取到一個絕對路徑的目錄,
 45     如絕對路徑:'C:\\test\\hongten.ini'
 46     則返回的是'C:\\test'
 47     '''
 48     if os.path.exists(absPath):
 49         if SHOW_LOG:
 50             print('the path [{}] existing!'.format(absPath))
 51         return os.path.split(absPath)[0]
 52     else:
 53         return os.path.split(absPath)[0]
 54 
 55 def get_config():
 56     '''return a configparser object'''
 57     return configparser.ConfigParser()
 58 
 59 def write_datas_2_config(path, config, datas):
 60     '''向指定的ini配置文件中寫入數據
 61     參數:
 62         path       -- 指定的ini配置文件路徑
 63         config     -- configparaser的一個對象
 64         datas      -- 配置文件的數據,類型為字典類型
 65                       在datas數據中有key,value,對於
 66                       每一個value來說都是字典類型,如:
 67                       datas = {'a' : {'1', '2'}
 68                       'b' : {'c', 'd', 'e'}}
 69         '''
 70     for k, v in datas.items():
 71         config[k] = v
 72     if SHOW_LOG:
 73         print('打開文件:[{}]'.format(path))
 74     with open(path, 'w') as cf:
 75         if SHOW_LOG:
 76             for name in config.sections():
 77                 c = ''
 78                 for key in config[name]:
 79                     c += key + ' : ' + config[name][key] + ','
 80                 print('寫入數據:[{}]\n[{}]'.format(name, c[0:-1]))
 81         config.write(cf)
 82 
 83 def write_config(path, config, name, data):
 84     '''向指定的ini配置文件中寫入數據
 85     參數:
 86         path       -- 指定的ini配置文件路徑
 87         config     -- configparaser的一個對象
 88         name       -- 配置項的root名稱
 89         data       -- 配置文件的數據,類型為字典類型
 90                       如:
 91                       data = {'a', 'b', 'c'}
 92     '''
 93     config[name] = data
 94     if SHOW_LOG:
 95         print('打開文件:[{}]'.format(path))
 96     with open(path, 'w') as cf:
 97         if SHOW_LOG:
 98             print('開始寫入數據:[{}]'.format(data))
 99         config.write(cf)
100 
101 def read_config(path, config, name):
102     '''讀取配置文件信息'''
103     if SHOW_LOG:
104         print('打開文件:[{}]'.format(path))
105     config.read(path)
106     sections = config.sections()
107     if name is not None and name != '' and name in sections:
108         content = ''
109         for key in config[name]:
110             if SHOW_LOG:
111                 print('開始讀取數據:[{}] = [{}]'.format(key, config[name][key]))
112             content += key + ' : ' + config[name][key] +','
113         return content[0:-1]
114     else:
115         print('name is Empty or equals None or not int sections!')
116     
117 def read_form_config(path, config):
118     '''讀取配置文件信息,以字典的形式返回'''
119     if SHOW_LOG:
120         print('打開文件:[{}]'.format(path))
121     config.read(path)
122     sections = config.sections()
123     #返回的字典對象
124     result_dict = {}
125     for name in sections:
126         #字典中每一個value都是一個字典對象
127         temp_dict = {}
128         if SHOW_LOG:
129             print('獲取模塊名稱:[{}]'.format(name))
130         for key in config[name]:
131             if SHOW_LOG:
132                 print('開始讀取數據:[{}] = [{}]'.format(key, config[name][key]))
133             temp_dict[key] = config[name][key]
134         result_dict[name] = temp_dict
135     return result_dict
136 
137 def get_value_from_config(path, config, name, key):
138     '''
139     從ini文件中獲取某個key所對應的value值
140     參數:
141         path       -- ini文件路徑
142         config     -- configparser對象
143         name       -- ini文件中的模塊名稱
144         key        -- 對應模塊中的key值
145     '''
146     if SHOW_LOG:
147         print('打開文件:[{}]'.format(path))
148     config.read(path)
149     sections =  config.sections()
150     if name is not None and name != '' and name in sections:
151         keys = []
152         for k in config[name]:
153             keys.append(k)
154         if key in keys:
155             if SHOW_LOG:
156                 print('獲取到[{}]文件,模塊:[{}],鍵:[{}],值:[{}]'.format(path, name, key, config[name][key]))
157             return config[name][key]
158         else:
159             print('不存在對應的key...')
160     else:
161         print('name is Empty or equals None or not int sections!')
162 
163 def init():
164     global SHOW_LOG
165     SHOW_LOG = True
166     print('SHOW_LOG : {}'.format(SHOW_LOG))
167     #Microsoft Windows INI files path
168     global HONGTEN_INT_PATH
169     HONGTEN_INT_PATH = 'C:\\test\\hongten.ini'
170     abspath = get_path(HONGTEN_INT_PATH)
171     mkdirs(abspath)
172     
173         
174 def main():
175     init()
176     data = {'name' : 'hongten_datasource',
177             'driverClassName' : 'oracle.jdbc.OracleDriver',
178             'isJndiDs' : 'false',
179             'ip' : '172.0.0.1',
180             'port' : '1521',
181             'dbName' : 'db_hongten',
182             'user' : 'root',
183             'password' : '*******',
184             'url' : 'jdbc:oracle:thin:@'}
185     prov_data = {'GD' : 'Guangdong',
186                  'SH' : 'Shanghai',
187                  'BJ' : 'Beijing',
188                  'ZJ' : 'Zhejiang'}
189     author_data = {'author' : 'hongten',
190                    'mailto' : 'hongtenzone@foxmail.com',
191                    'blog' : 'http://www.cnblogs.com/hongten',
192                    'qq' : '648719819',
193                    'create' : '2013-08-22',
194                    'version' : '1.0'}
195     datas = {'DATA_SOURCE_INFO' : data,
196              'PROVINCES' : prov_data,
197              'AUTHOR_INFO' : author_data}
198     name = 'DATA_SOURCE_INFO'
199     key = 'name'
200     config = get_config()
201     write_config(HONGTEN_INT_PATH, config, name, data)
202     content = read_config(HONGTEN_INT_PATH, config, name)
203     print(content)
204     print('#' * 50)
205     write_datas_2_config(HONGTEN_INT_PATH, config, datas)
206     content = read_form_config(HONGTEN_INT_PATH, config)
207     print(content)
208     print('#' * 50)
209     value = get_value_from_config(HONGTEN_INT_PATH, config, name, key)
210     print(value)
211     
212 if __name__ == '__main__':
213     main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM