#
# 最近出了一趟差,是从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': '', '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': '', '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': '', 'version': '1.0'}}
##################################################
打开文件:[C:\test\hongten.ini]
获取到[C:\test\hongten.ini]文件,模块:[DATA_SOURCE_INFO],键:[name],值:[hongten_datasource]
hongten_datasource
>>>

在c:\\test目录下面的情况:

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

代码部分:

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

 #python configparser

 #Author  : Hongten
#Mailto : hongtenzone@foxmail.com
#Blog : http://www.cnblogs.com/hongten
#QQ : 648719819
#Create : 2013-08-22
#Version : 1.0 import os
import configparser '''
在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. 以下实现的功能是:
将一些配置信息写入到指定文件中,并且提供方法获取配置文件中的信息
''' #global var
SHOW_LOG = True
#Microsoft Windows INI files path
HONGTEN_INT_PATH = '' def mkdirs(path):
'''创建多级目录'''
if os.path.exists(path):
if SHOW_LOG:
print('The path [{}] existing!'.format(path))
else:
if SHOW_LOG:
print('The path [{}] dosen\'t exist!'.format(path))
os.makedirs(path)
if SHOW_LOG:
print('Created the path [{}]'.format(path)) def get_path(absPath):
'''获取到一个绝对路径的目录,
如绝对路径:'C:\\test\\hongten.ini'
则返回的是'C:\\test'
'''
if os.path.exists(absPath):
if SHOW_LOG:
print('the path [{}] existing!'.format(absPath))
return os.path.split(absPath)[0]
else:
return os.path.split(absPath)[0] def get_config():
'''return a configparser object'''
return configparser.ConfigParser() def write_datas_2_config(path, config, datas):
'''向指定的ini配置文件中写入数据
参数:
path -- 指定的ini配置文件路径
config -- configparaser的一个对象
datas -- 配置文件的数据,类型为字典类型
在datas数据中有key,value,对于
每一个value来说都是字典类型,如:
datas = {'a' : {'1', '2'}
'b' : {'c', 'd', 'e'}}
'''
for k, v in datas.items():
config[k] = v
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
with open(path, 'w') as cf:
if SHOW_LOG:
for name in config.sections():
c = ''
for key in config[name]:
c += key + ' : ' + config[name][key] + ','
print('写入数据:[{}]\n[{}]'.format(name, c[0:-1]))
config.write(cf) def write_config(path, config, name, data):
'''向指定的ini配置文件中写入数据
参数:
path -- 指定的ini配置文件路径
config -- configparaser的一个对象
name -- 配置项的root名称
data -- 配置文件的数据,类型为字典类型
如:
data = {'a', 'b', 'c'}
'''
config[name] = data
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
with open(path, 'w') as cf:
if SHOW_LOG:
print('开始写入数据:[{}]'.format(data))
config.write(cf) def read_config(path, config, name):
'''读取配置文件信息'''
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
config.read(path)
sections = config.sections()
if name is not None and name != '' and name in sections:
content = ''
for key in config[name]:
if SHOW_LOG:
print('开始读取数据:[{}] = [{}]'.format(key, config[name][key]))
content += key + ' : ' + config[name][key] +','
return content[0:-1]
else:
print('name is Empty or equals None or not int sections!') def read_form_config(path, config):
'''读取配置文件信息,以字典的形式返回'''
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
config.read(path)
sections = config.sections()
#返回的字典对象
result_dict = {}
for name in sections:
#字典中每一个value都是一个字典对象
temp_dict = {}
if SHOW_LOG:
print('获取模块名称:[{}]'.format(name))
for key in config[name]:
if SHOW_LOG:
print('开始读取数据:[{}] = [{}]'.format(key, config[name][key]))
temp_dict[key] = config[name][key]
result_dict[name] = temp_dict
return result_dict def get_value_from_config(path, config, name, key):
'''
从ini文件中获取某个key所对应的value值
参数:
path -- ini文件路径
config -- configparser对象
name -- ini文件中的模块名称
key -- 对应模块中的key值
'''
if SHOW_LOG:
print('打开文件:[{}]'.format(path))
config.read(path)
sections = config.sections()
if name is not None and name != '' and name in sections:
keys = []
for k in config[name]:
keys.append(k)
if key in keys:
if SHOW_LOG:
print('获取到[{}]文件,模块:[{}],键:[{}],值:[{}]'.format(path, name, key, config[name][key]))
return config[name][key]
else:
print('不存在对应的key...')
else:
print('name is Empty or equals None or not int sections!') def init():
global SHOW_LOG
SHOW_LOG = True
print('SHOW_LOG : {}'.format(SHOW_LOG))
#Microsoft Windows INI files path
global HONGTEN_INT_PATH
HONGTEN_INT_PATH = 'C:\\test\\hongten.ini'
abspath = get_path(HONGTEN_INT_PATH)
mkdirs(abspath) def main():
init()
data = {'name' : 'hongten_datasource',
'driverClassName' : 'oracle.jdbc.OracleDriver',
'isJndiDs' : 'false',
'ip' : '172.0.0.1',
'port' : '',
'dbName' : 'db_hongten',
'user' : 'root',
'password' : '*******',
'url' : 'jdbc:oracle:thin:@'}
prov_data = {'GD' : 'Guangdong',
'SH' : 'Shanghai',
'BJ' : 'Beijing',
'ZJ' : 'Zhejiang'}
author_data = {'author' : 'hongten',
'mailto' : 'hongtenzone@foxmail.com',
'blog' : 'http://www.cnblogs.com/hongten',
'qq' : '',
'create' : '2013-08-22',
'version' : '1.0'}
datas = {'DATA_SOURCE_INFO' : data,
'PROVINCES' : prov_data,
'AUTHOR_INFO' : author_data}
name = 'DATA_SOURCE_INFO'
key = 'name'
config = get_config()
write_config(HONGTEN_INT_PATH, config, name, data)
content = read_config(HONGTEN_INT_PATH, config, name)
print(content)
print('#' * 50)
write_datas_2_config(HONGTEN_INT_PATH, config, datas)
content = read_form_config(HONGTEN_INT_PATH, config)
print(content)
print('#' * 50)
value = get_value_from_config(HONGTEN_INT_PATH, config, name, key)
print(value) if __name__ == '__main__':
main()

python开发_configparser_解析.ini配置文件工具_完整版_博主推荐的更多相关文章

  1. python开发_xml.dom_解析XML文档_完整版_博主推荐

    在阅读之前,你需要了解一些xml.dom的一些理论知识,在这里你可以对xml.dom有一定的了解,如果你阅读完之后. 下面是我做的demo 运行效果: 解析的XML文件位置:c:\\test\\hon ...

  2. python开发_csv(Comma Separated Values)_逗号分隔值_常用导入导出格式_完整版_博主推荐

    ## 最近出了一趟差,是从20号去的,今天回来...# 就把最近学习的python内容给大家分享一下...#''' 在python中,CSV(Comma Separated Values),从字面上面 ...

  3. python开发_gzip_压缩|解压缩gz文件_完整版_博主推荐

    ''' gzip -- 支持gzip文件 源文件:Lib/gzip.py 这个模块提供了一些简单的接口来对文件进行压缩和解压缩,类似于GNU项目的gzip和gunzip. 数据的压缩源于zlib模块的 ...

  4. python开发_tkinter_菜单选项中英文切换_菜单选项不可用操作_博主推荐

    我使用的python版本为:3.3.2 如果你对python中tkinter模块的菜单操作不是很了解,你可以看看: python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推 ...

  5. python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推荐(二)

    在上一篇blog:python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推荐 中介绍了python中的tkinter的一些东西,你可能对tkinter有一定的了解了.这篇b ...

  6. 大数据搭建各个子项目时配置文件技巧(适合CentOS和Ubuntu系统)(博主推荐)

    不多说,直接上干货! 很多同行,也许都知道,对于我们大数据搭建而言,目前主流,分为Apache 和 Cloudera 和 Ambari. 后两者我不多说,是公司必备和大多数高校科研环境所必须的! 分别 ...

  7. Ubuntu14.04下Mongodb数据库可视化工具安装部署步骤(图文详解)(博主推荐)

    不多说,直接上干货! 前期博客 Ubuntu14.04下Mongodb(离线安装方式|非apt-get)安装部署步骤(图文详解)(博主推荐) Ubuntu14.04下Mongodb官网安装部署步骤(图 ...

  8. 精通Android4.0开发视频【张泽华】-完整版下载

    观看须知: 本视频教程为黑马程序员 张泽华老师历经2年时间整理 适合有JavaWeb基础同学学习,教程采用的AVI方式发布,所以看起来很流畅. 视频概括: 1. 本套视频不同于市面上任何一套andro ...

  9. python读取uti-8格式ini配置文件出现UnicodeDecodeError: 'gbk' codec can't decode byte 0xba in position 367: illegal multibyte sequence错误解决方法

    出现这种错误只需要在read下添加encoding='utf-8' 如: from configparser import ConfigParser cf = ConfigParser() cf.re ...

随机推荐

  1. APUE-文件和目录(八)文件时间

    文件的时间 与文件相关的三个时间值: 访问时间:最后一次访问文件的时间.例如,cat命令会修改这个时间. 修改时间:文件内容最后一次被修改的时间. 状态更改时间:文件的i节点最后一次被修改的时间.例如 ...

  2. 四、Springboot Debug调试

    描述: 在使用maven插件执行spring-boot:run进行启动的时候,如果设置的断点进不去,要进行以下的设置. 1.添加jvm参数配置 在spring-boot的maven插件加上jvmArg ...

  3. npm 下载node-zookeeper包

    环境:centos7(lunix) 1.安装nvm curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install. ...

  4. scrapy shell命令的【选项】简介

    在使用scrapy shell测试某网站时,其返回400 Bad Request,那么,更改User-Agent请求头信息再试. DEBUG: Crawled () <GET https://w ...

  5. ASP .Net Core系统部署到SUSE 16 Linux Enterprise Server 12 SP2 64 具体方案

    .Net Core 部署到 SUSE 16 Linux Enterprise Server 12 SP2 64 位中的步骤 1.安装工具 1.apache 2..Net Core(dotnet-sdk ...

  6. Codeforces 793C - Mice problem(几何)

    题目链接:http://codeforces.com/problemset/problem/793/C 题目大意:给你一个捕鼠器坐标,和各个老鼠的的坐标以及相应坐标的移动速度,问你是否存在一个时间点可 ...

  7. Linux学习笔记:vi常用命令

    在Linux系统中常用vi命令进行文本编辑. vi命令是UNIX操作系统和类UNIX操作系统中最通用的全屏幕纯文本编辑器.Linux中的vi编辑器叫vim,它是vi的增强版(vi Improved), ...

  8. 一个文件系统过滤驱动的demo

    因为没写过FSD过滤驱动,所以拿来练练手,没有什么技术含量.参考自Win内核安全与驱动开发. 先梳理一下大概的流程,就是怎么去绑定设备栈.怎么去过滤各种请求的. 首先肯定是要绑定设备栈的,来看下怎么绑 ...

  9. CCF CSP 201509-3 模板生成系统

    CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址 CCF CSP 201509-3 模板生成系统 问题描述 成成最近在搭建一个网站,其中一些页面的部分内容来自数据 ...

  10. 饼图tooltip

    @{ ViewBag.Title = "pie"; } <h2>pie</h2> <div id="main" style=&qu ...