1 #!/usr/bin/env python
2 # coding=utf-8
3 __author__ = 'Luzhuo'
4 __date__ = '2017/5/26'
5 # config_configparser.py 配置文件
6 # configparser 可以读写和解析注释文件, 但是没有写入注释的功能
7
8 import configparser
9 import re
10
11
12 config_str = '''
13 # 配置文件信息案例
14 [DEFAULT]
15 minSdkVersion = 15
16 targetSdkVersion = 24
17 versionName = 1.0.0
18 server action = yes
19
20 [luzhuo.me]
21 user = luzhuo
22
23 # This is a comments.
24 [mysql]
25 ip = 127.0.0.1
26 port = 3306
27 '''
28
29 def config_write():
30 '''
31 生成配置文件, 字典的形式添加数据
32 '''
33
34 config = configparser.ConfigParser()
35
36 config['DEFAULT'] = {'minSdkVersion': '15',
37 'targetSdkVersion': '24',
38 'versionName': '1.0.0',
39 'server action': 'yes'}
40
41 config['luzhuo.me'] = {}
42 config['luzhuo.me']['user'] = 'luzhuo'
43
44 config['mysql'] = {}
45 topsecret = config['mysql']
46 topsecret['ip'] = '127.0.0.1'
47 topsecret['port'] = '3306'
48
49 with open('config.ini', 'w') as configfile:
50 config.write(configfile)
51
52
53 def config_read():
54 '''
55 解析配置文件
56 '''
57
58 # 读取
59 config = configparser.ConfigParser()
60 config.read('config.ini')
61
62 lists_header = config.sections() # 配置组名, ['luzhuo.me', 'mysql'] # 不含'DEFAULT'
63 print(lists_header)
64
65 boolean = 'luzhuo.me' in config # 配置组是否存在
66 boolean = config.has_section("luzhuo.me")
67 print(boolean)
68
69 user = config['luzhuo.me']['user']
70 print(user)
71 mysql = config['mysql']
72 mysql_ip = mysql['ip']
73 mysql_port = mysql['port']
74 print(mysql_ip, ":", mysql_port)
75
76 for key in config['luzhuo.me']: # 遍历配置组的key, 与'DEFAULT'组的key
77 print(key)
78
79 # 删除
80 sec = config.remove_section("luzhuo.me") # 删除
81 config.write(open("config.ini", "w")) # 写回去
82
83 # 添加
84 config.add_section("web.server")
85 config.write(open("config.ini", "w"))
86
87 # 修改/添加
88 config.set("web.server", "http", "http://luzhuo.me")
89 config.write(open("config.ini", "w"))
90
91 # 删除key
92 config.remove_option("mysql", "ip")
93 config.write(open("config.ini", "w"))
94
95
96 def config_func():
97 '''
98 写入的值均为字符串
99 配合文件的节名称区分大小写, 键不区分大小写(可任意缩进), 注释用'#'和';'(用作整行前缀,可缩进,不推荐行内注释), 值可以跨越多行(要缩进,慎用), 键值分隔符'='和':'
100 DEFAULT无法移除,试图删除将引发ValueError, clear()保持原样, popitem()不返回
101 '''
102
103 # --- ConfigParser 对象 ---
104 # 配置解析器, defaults:DEFAULT字典, dict_type:字典类型(默认:有序字典), allow_no_value:True是否接收不带值的选项(值为None),(默认False), delimiters:键值分隔符, comment_prefixes:整行注释符, inline_comment_prefixes:行内注释符(值之后), strict:是否去重:True(默认), empty_lines_in_values:值是否可以多行;(默认True),False(行标记选项的结尾), default_section:默认节的名称'DEFAULT', interpolation:插值, converters:转换器{类型转换器的名称, 从字符串转换所需数据的类型}{'dicimal': decimal.Decimal}
105 # class configparser.ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})
106 config = configparser.ConfigParser()
107
108 # items(raw=False, vars=None) # 所有节(含DEFAULT) ItemsView(section_name, section_proxy)(可遍历对象)
109 ItemsView = config.items()
110 dicts = config.defaults() # DEFAULT字典
111 lists = config.sections() # 可用的节列表(不含DEFAULT)
112 # has_section(section) # 是否存在该节
113 boolean = config.has_section("mysql")
114 lists = config.options("mysql") # 指定节的选项列表(含DEFAULT)
115 boolean = config.has_option("mysql", "ip") # 是否存在指定节的选项
116
117 # read(filenames, encoding=None) # 尝试读取和解析文件名列表(不存在则忽略), 加载初始值调用read_file()要在read()之前调用
118 config.read("config.ini", encoding="utf-8-sig") # windows下用记事本保存utf8格式要用utf-8-sig编码集
119 # read_file(f, source=None) # 从f读取和解析配置数据, source:文件名
120 config.read_file(open('config.ini', encoding="utf-8-sig"))
121 # read_string(string, source='<string>') # 从字符串解析配置数据
122 config.read_string(config_str)
123 # read_dict(dictionary, source='<dict>') # 读取字典
124 config.read_dict({'section1': {'key1': 'value1',
125 'key2': 'value2'},
126 'section2': {'key3': 'value3',
127 'key4': 'value4'}
128 })
129
130 # get(section, option, *, raw=False, vars=None[, fallback]) # 获取指定节的选项值, fallback:为找到选项时的返回值
131 data_str = config.get("mysql", "ip", fallback=None)
132 # getint(section, option, *, raw=False, vars=None[, fallback]) # 获取整数(选项的值强转为整数)
133 data_int = config.getint("mysql", "port", fallback=-1)
134 # getfloat(section, option, *, raw=False, vars=None[, fallback])
135 data = float = config.getfloat("mysql", "port", fallback=-1)
136 # getboolean(section, option, *, raw=False, vars=None[, fallback])
137 data_bool = config.getboolean("DEFAULT", "server action", fallback=False) # 获取布尔值,不区分大小写,识别'yes'/'no','on'/'off','true'/'false','1'/'0'
138
139 # write(fileobject, space_around_delimiters=True) # 将配置写入文件, space_around_delimiters:是否用空格分隔键值之间
140 config.write(open("config.ini", "w", encoding="utf-8"))
141 # add_section(section) # 添加节, 节重复DuplicateSectionError, 与默认节重复ValueError, 不是字符串TypeError
142 config.add_section("server.luzhuo.me")
143 # remove_section(section) # 删除节, 存在True,不存在False
144 boolean = config.remove_section("server.luzhuo.me")
145 # set(section, option, value) # 给指定的节设置值, 节不存在NoSectionError, option和value:选项和值为字符串,否则TypeError
146 config.set("server.luzhuo.me", "ip", "127.0.0.1")
147 # remove_option(section, option) # 删除选型, 不存在节NoSectionError, 选项存在True,不存在False
148 boolean = config.remove_option("server.luzhuo.me", "ip")
149
150 # optionxform(option) # 子类重写该方法, 或 config.optionxform = str(str区分大小写) 修改, 用于选项名称转为在内部结构中使用的实现
151
152 configparser.MAX_INTERPOLATION_DEPTH # 使用默认插值时, 当raw=false,get()递归插值的最大深度
153
154 config.clear() # 所有节都包含'DEFAULT'值,对节的清空不会删除'DEFAULT'值
155 config.BOOLEAN_STATES.update({'enabled': True, 'disabled': False}) # 自定义boolean的判断
156 config.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") # 自定义节头的编译与解析的正则表达式(去除左右空格)
157
158
159
160 # --- 异常 ---
161 try: pass
162 except configparser.Error: pass # configparser异常的基类
163 except configparser.NoSectionError: pass # 未找到指定节
164 except configparser.DuplicateSectionError: pass # 节重复
165 except configparser.DuplicateOptionError: pass # 选项重复
166 except configparser.NoOptionError: pass # 未找到指定选项
167 except configparser.InterpolationError: pass # 插值异常的基类
168 except configparser.InterpolationDepthError: pass # 迭代次数超过MAX_INTERPOLATION_DEPTH
169 except configparser.InterpolationMissingOptionError: pass # 选项不存在
170 except configparser.InterpolationSyntaxError: pass # 替换源文本不符合语法
171 except configparser.MissingSectionHeaderError: pass # 没有节头
172 except configparser.ParsingError: pass # 解析文件错误
173
174
175
176 if __name__ == "__main__":
177 config_write()
178 config_read()
179
180 # config_func()

pyhton3 configparser模块的更多相关文章

  1. configparser模块

    configparser模块 echo   $@ $# $? $* configparse用于处理特定格式的文件,其本质上利用open来操作文件(比如配置文件) **********配置文件***** ...

  2. 用ConfigParser模块读写配置文件——Python

    对于功能较多.考虑用户体验的程序,配置功能是必不可少的,如何存储程序的各种配置? 1)可以用全局变量,不过全局变量具有易失性,程序崩溃或者关闭之后配置就没了,再者配置太多,将变量分配到哪里也是需要考虑 ...

  3. Python自动化测试 -ConfigParser模块读写配置文件

    C#之所以容易让人感兴趣,是因为安装完Visual Studio, 就可以很简单的直接写程序了,不需要做如何配置. 对新手来说,这是非常好的“初体验”, 会激发初学者的自信和兴趣. 而有些语言的开发环 ...

  4. Python学习笔记——基础篇【第六周】——PyYAML & configparser模块

    PyYAML模块 Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 常用模块之Co ...

  5. Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...

  6. 小白的Python之路 day5 configparser模块的特点和用法

    configparser模块的特点和用法 一.概述 主要用于生成和修改常见配置文件,当前模块的名称在 python 3.x 版本中变更为 configparser.在python2.x版本中为Conf ...

  7. configparser模块的常见用法

    configparser模块用于生成与windows.ini文件类似格式的配置文件,可以包含一节或多节(section),每个节可以有一个或多个参数(键=值) 在学习这个模块之前,先来看一个经常见到的 ...

  8. day20 hashlib、hmac、subprocess、configparser模块

    hashlib模块:加密 import hashlib# 基本使用cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8'))print(cipher.h ...

  9. python封装configparser模块获取conf.ini值(优化版)

    昨天晚上封装了configparser模块,是根据keyname获取的value.python封装configparser模块获取conf.ini值 我原本是想通过config.ini文件中的sect ...

随机推荐

  1. string::find_last_of

    今天在代码中用到string的这个方法,一不小心就用错了. 这是http://www.cplusplus.com/关于这个方法的解释. Find character in string from th ...

  2. windows下使用python2.7.6 安装django

    1) 安装python2.7.6 2) 由于 python2.7.6 中没有安装setuptools,需要先从官网下载setuptools,下载zip包然后解压,运行 python setup.py ...

  3. the method getcontextpath() from the type httpservletrequest refers to the missing type string

    导入项目的时候容易报出这个错误,主要因为JRE(jdk版本不一致). 解决方法:就是重新配置路径,配置你机器上安装的jdk. 右击该出错项目→ Build Path → Configure Build ...

  4. linux系统下crontab 配置启动定时任务

    1 crontab -e 配置启动定时任务 */1 * * * * sh /home/admin/application/wd/core-python/getMemPositionFromAnaual ...

  5. fzu 2250 不可能弹幕结界 分析+模拟,考察思维严谨。

    Problem 2250 不可能弹幕结界 Accept: 5    Submit: 13Time Limit: 1000 mSec    Memory Limit : 65536 KB Problem ...

  6. OpenCV中Kinect的使用(2)

    接OpenCV中Kinect的使用(1),主要讲述OpenCV中关于Kinect接口(类 VideoCapture )的一些使用介绍. 类 VideoCapture 支持Kinect传感器.使用 Vi ...

  7. [浪风转载]Jquery取得iframe中元素的几种方法

    iframe在复合文档中经常用到,利用jquery操作iframe可以大幅提高效率,这里收集一些基本操作 DOM方法:父窗口操作IFRAME:window.frames["iframeSon ...

  8. VLC 媒体播放器

    VLC 媒体播放器 VLC 媒体播放器是一个便携式. 免费.开源. 跨平台的媒体播放器. VideoLAN 项目的流式媒体服务器.分为Windows Phone版本和Android版本. 下载地址: ...

  9. 关于自我总结的html5新特性

    最近本包子制订了一个学校计划,第一步就是了解并总结一下html5现在所含有的新特性,好吧,这只是一个了解,- -! 自己总结了一个word文档,里面很多东西自己都还没实际用过,下一步,本包子要写pc端 ...

  10. 巨蟒django之CRM1 需求分析&&表结构设计&&注册登录验证

    1.需求分析 .项目 ()业务 ()权限的管理 .CRM customer relationship management 客户关系管理系统 .谁来使用CRM? 销售&&班主任& ...