本文由 Luzhuo 編寫,轉發請保留該信息.?
原文:?http://blog.csdn.net/rozol/article/details/72793304
?
以下代碼以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() ?
轉載于:https://www.cnblogs.com/dion-90/p/7978081.html
總結
以上是生活随笔為你收集整理的Python3 配置文件(configparser)(转载)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。