示例python版本:3.6python
示例中註釋詳細mysql
#!/usr/bin/env python # coding=utf-8 __author__ = 'Luzhuo' __date__ = '2017/5/26' # config_configparser.py 配置文件 # configparser 能夠讀寫和解析註釋文件, 可是沒有寫入註釋的功能 import configparser import re config_str = ''' # 配置文件信息案例 [DEFAULT] minSdkVersion = 15 targetSdkVersion = 24 versionName = 1.0.0 server action = yes [luzhuo.me] user = luzhuo # This is a comments. [mysql] ip = 127.0.0.1 port = 3306 ''' def config_write(): ''' 生成配置文件, 字典的形式添加數據 ''' config = configparser.ConfigParser() config['DEFAULT'] = {'minSdkVersion': '15', 'targetSdkVersion': '24', 'versionName': '1.0.0', 'server action': 'yes'} config['luzhuo.me'] = {} config['luzhuo.me']['user'] = 'luzhuo' config['mysql'] = {} topsecret = config['mysql'] topsecret['ip'] = '127.0.0.1' topsecret['port'] = '3306' with open('config.ini', 'w') as configfile: config.write(configfile) def config_read(): ''' 解析配置文件 ''' # 讀取 config = configparser.ConfigParser() config.read('config.ini') lists_header = config.sections() # 配置組名, ['luzhuo.me', 'mysql'] # 不含'DEFAULT' print(lists_header) boolean = 'luzhuo.me' in config # 配置組是否存在 boolean = config.has_section("luzhuo.me") print(boolean) user = config['luzhuo.me']['user'] print(user) mysql = config['mysql'] mysql_ip = mysql['ip'] mysql_port = mysql['port'] print(mysql_ip, ":", mysql_port) for key in config['luzhuo.me']: # 遍歷配置組的key, 與'DEFAULT'組的key print(key) # 刪除 sec = config.remove_section("luzhuo.me") # 刪除 config.write(open("config.ini", "w")) # 寫回去 # 添加 config.add_section("web.server") config.write(open("config.ini", "w")) # 修改/添加 config.set("web.server", "http", "http://luzhuo.me") config.write(open("config.ini", "w")) # 刪除key config.remove_option("mysql", "ip") config.write(open("config.ini", "w")) def config_func(): ''' 寫入的值均爲字符串 配合文件的節名稱區分大小寫, 鍵不區分大小寫(可任意縮進), 註釋用'#'和';'(用做整行前綴,可縮進,不推薦行內註釋), 值能夠跨越多行(要縮進,慎用), 鍵值分隔符'='和':' DEFAULT沒法移除,試圖刪除將引起ValueError, clear()保持原樣, popitem()不返回 ''' # --- ConfigParser 對象 --- # 配置解析器, 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} # 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={}) config = configparser.ConfigParser() # items(raw=False, vars=None) # 全部節(含DEFAULT) ItemsView(section_name, section_proxy)(可遍歷對象) ItemsView = config.items() dicts = config.defaults() # DEFAULT字典 lists = config.sections() # 可用的節列表(不含DEFAULT) # has_section(section) # 是否存在該節 boolean = config.has_section("mysql") lists = config.options("mysql") # 指定節的選項列表(含DEFAULT) boolean = config.has_option("mysql", "ip") # 是否存在指定節的選項 # read(filenames, encoding=None) # 嘗試讀取和解析文件名列表(不存在則忽略), 加載初始值調用read_file()要在read()以前調用 config.read("config.ini", encoding="utf-8-sig") # windows下用記事本保存utf8格式要用utf-8-sig編碼集 # read_file(f, source=None) # 從f讀取和解析配置數據, source:文件名 config.read_file(open('config.ini', encoding="utf-8-sig")) # read_string(string, source='<string>') # 從字符串解析配置數據 config.read_string(config_str) # read_dict(dictionary, source='<dict>') # 讀取字典 config.read_dict({'section1': {'key1': 'value1', 'key2': 'value2'}, 'section2': {'key3': 'value3', 'key4': 'value4'} }) # get(section, option, *, raw=False, vars=None[, fallback]) # 獲取指定節的選項值, fallback:爲找到選項時的返回值 data_str = config.get("mysql", "ip", fallback=None) # getint(section, option, *, raw=False, vars=None[, fallback]) # 獲取整數(選項的值強轉爲整數) data_int = config.getint("mysql", "port", fallback=-1) # getfloat(section, option, *, raw=False, vars=None[, fallback]) data = float = config.getfloat("mysql", "port", fallback=-1) # getboolean(section, option, *, raw=False, vars=None[, fallback]) data_bool = config.getboolean("DEFAULT", "server action", fallback=False) # 獲取布爾值,不區分大小寫,識別'yes'/'no','on'/'off','true'/'false','1'/'0' # write(fileobject, space_around_delimiters=True) # 將配置寫入文件, space_around_delimiters:是否用空格分隔鍵值之間 config.write(open("config.ini", "w", encoding="utf-8")) # add_section(section) # 添加節, 節重複DuplicateSectionError, 與默認節重複ValueError, 不是字符串TypeError config.add_section("server.luzhuo.me") # remove_section(section) # 刪除節, 存在True,不存在False boolean = config.remove_section("server.luzhuo.me") # set(section, option, value) # 給指定的節設置值, 節不存在NoSectionError, option和value:選項和值爲字符串,不然TypeError config.set("server.luzhuo.me", "ip", "127.0.0.1") # remove_option(section, option) # 刪除選型, 不存在節NoSectionError, 選項存在True,不存在False boolean = config.remove_option("server.luzhuo.me", "ip") # optionxform(option) # 子類重寫該方法, 或 config.optionxform = str(str區分大小寫) 修改, 用於選項名稱轉爲在內部結構中使用的實現 configparser.MAX_INTERPOLATION_DEPTH # 使用默認插值時, 當raw=false,get()遞歸插值的最大深度 config.clear() # 全部節都包含'DEFAULT'值,對節的清空不會刪除'DEFAULT'值 config.BOOLEAN_STATES.update({'enabled': True, 'disabled': False}) # 自定義boolean的判斷 config.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") # 自定義節頭的編譯與解析的正則表達式(去除左右空格) # --- 異常 --- try: pass except configparser.Error: pass # configparser異常的基類 except configparser.NoSectionError: pass # 未找到指定節 except configparser.DuplicateSectionError: pass # 節重複 except configparser.DuplicateOptionError: pass # 選項重複 except configparser.NoOptionError: pass # 未找到指定選項 except configparser.InterpolationError: pass # 插值異常的基類 except configparser.InterpolationDepthError: pass # 迭代次數超過MAX_INTERPOLATION_DEPTH except configparser.InterpolationMissingOptionError: pass # 選項不存在 except configparser.InterpolationSyntaxError: pass # 替換源文本不符合語法 except configparser.MissingSectionHeaderError: pass # 沒有節頭 except configparser.ParsingError: pass # 解析文件錯誤 if __name__ == "__main__": config_write() config_read() # config_func()