码迷,mamicode.com
首页 > 其他好文 > 详细

configparser模块

时间:2018-02-10 18:52:32      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:import   head   conf   inter   配置文件信息   less   object   bin   python   

以下代码以Python3.6.1为例 

Less is more! 
configparser
可以读写和解析注释文件, 但是没有写入注释的功能

技术分享图片

 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()

技术分享图片

 

configparser模块

标签:import   head   conf   inter   配置文件信息   less   object   bin   python   

原文地址:https://www.cnblogs.com/hhjwqh/p/8439312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!