前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python开发_configparser_解析.ini配置文件工具_完整版_博主推荐

python开发_configparser_解析.ini配置文件工具_完整版_博主推荐

作者头像
Hongten
发布2018-09-13 12:18:16
5260
发布2018-09-13 12:18:16
举报
文章被收录于专栏:HongtenHongten
代码语言:javascript
复制
#
#   最近出了一趟差,是从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,

运行效果:

代码语言:javascript
复制
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目录下面的情况:

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

代码部分:

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

代码语言:javascript
复制
  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()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-08-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档