python configparser配置文件解析器使用詳解


來源:https://blog.csdn.net/weixin_42174361/article/details/82873878

configparser簡介

原文引用1
原文引用2
python2下該模塊名為ConfigParser,到3才改為configparser,可以看官方ConfigParser模塊的說明
ConfigParse 官方文檔

python3中configparser模塊的使用,configparser模塊是用來解析ini配置文件的解析器,關於ini配置文件的結構可以看python官方文檔中的介紹:
ini文件結構

ini文件結構需要注意一下幾點:

  • 鍵值對可用=或者:進行分隔
  • section的名字是區分大小寫的,而key的名字是不區分大小寫的
  • 鍵值對中頭部和尾部的空白符會被去掉
  • 值可以為多行
  • 配置文件可以包含注釋,注釋以#或者;為前綴

注意:configparserdefault_section的概念,默認為[DEFAULT]節,也就是之后的所有的section都有該默認section中的鍵值對,詳情參見configparser源碼的__init__()方法

基本使用

為了創建如下ini文件:
configparser模塊主要使用ConfigParser類來解析ini文件

[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no 

 

我們可以使用如下代碼:

>>> import configparser >>> config = configparser.ConfigParser() >>> config['DEFAULT'] = {'ServerAliveInterval': '45', ... 'Compression': 'yes', ... 'CompressionLevel': '9'} >>> config['bitbucket.org'] = {} >>> config['bitbucket.org']['User'] = 'hg' >>> config['topsecret.server.com'] = {} >>> topsecret = config['topsecret.server.com'] >>> topsecret['Port'] = '50022' # mutates the parser >>> topsecret['ForwardX11'] = 'no' # same here >>> config['DEFAULT']['ForwardX11'] = 'yes' >>> with open('example.ini', 'w') as configfile: ... config.write(configfile) 

 

然后我們再讀取該ini文件:

>>> import configparser >>> config = configparser.ConfigParser() >>> config.sections() [] >>> config.read('example.ini') ['example.ini'] >>> config.sections() ['bitbucket.org', 'topsecret.server.com'] >>> 'bitbucket.org' in config True >>> 'bytebong.com' in config False >>> config['bitbucket.org']['User'] 'hg' >>> config['DEFAULT']['Compression'] 'yes' >>> topsecret = config['topsecret.server.com'] >>> topsecret['ForwardX11'] 'no' >>> topsecret['Port'] '50022' >>> for key in config['bitbucket.org']: print(key) ... user compressionlevel serveraliveinterval compression forwardx11 >>> config['bitbucket.org']['ForwardX11'] 'yes' 

 

除了可以使用列表的方式獲取值,也可以通過section級別的get()方法獲取,同時該函數可以指定默認值

>>> topsecret.get('Port') '50022' >>> topsecret.get('CompressionLevel') '9' >>> topsecret.get('Cipher', '3des-cbc') '3des-cbc' 

 

而解析器級別的get()函數的默認值是通過fallback參數指定的:

>>> config.get('bitbucket.org', 'monster', ... fallback='No such things as monsters') 'No such things as monsters' 

 

需要注意的是,無論是通過列表方式獲取值,還是通過get()方法獲取值,獲取到的數據都字符串類型,如果想要獲取指定類型的數據,可以使用如下的幾個方法:

  • getint()
  • getfloat()
  • getboolean()

同時需要注意getboolean()方法能判斷True/False的值有: ‘yes’/‘no’, ‘on’/‘off’, ‘true’/‘false’ 和 ‘1’/‘0’

Interpolation

創建ConfigParser()類的時候可以指定interpolation參數,如果將interpolation設置為BasicInterpolation(),則配置文件中的%(key)s結構會被解析,如,比如example.ini文件內容如下:

[Paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures 

 

>>> import configparser >>> config = configparser.ConfigParser(interpolation=configparser.BasicInterpolation()) >>> config.read(r'F:\coding\python\example.ini') ['F:\\coding\\python\\example.ini'] >>> config['Paths']['my_dir'] '/Users/lumberjack' 

 

可以看到%(home_dir)s被解析成了/Users,說白了,相當於配置文件中的變量

創建ConfigParser()類的時候如果沒有指定interpolation參數,則不會解析%(key)s,只會返回字符串而已

>>> config['Paths']['my_dir'] '%(home_dir)s/lumberjack' 

 

 

當然Interpolation還有更高級的使用方法,創建ConfigParser()類的時候指定interpolation參數為ExtendedInterpolation(),那么解析器會解析${section:key}結構,那么上面的ini文件應該寫成如下的格式:

[Paths] home_dir: /Users my_dir: ${home_dir}/lumberjack my_pictures: ${my_dir}/Pictures 

 

 

並且ExtendedInterpolation()也能解析更復雜的,像下面這樣的ini文件:

[Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: ${Common:system_dir}/Library/Frameworks/ [Arthur] nickname: Two Sheds last_name: Jackson my_dir: ${Common:home_dir}/twosheds my_pictures: ${my_dir}/Pictures python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} 

 

 

ConfigParser

ConfigParser對象的其他方法,如:

  • add_section(section)
  • has_section(section)
  • options(section)
  • has_option(section, option)
  • remove_option(section, option)
  • remove_section(section)

都很常用,具體就不介紹了,看名字就知道是干什么的了

Python2.7 ConfigParser

該模塊用來解析Microsoft Windows INI文件,就是我們平常所說的ini文件。INI文件是一種按照特點方式排列的文本文件。每一個INI文件結構都非常類似,由若干段落(section)組成,在每個帶括號的標題下面,是若干個以單個單詞開頭的關鍵詞(keyword)和一個等號,等號右邊的就是關鍵字對應的值(value)。其一般形式如下:

[Section1] KeyWord1 = Valuel KeyWord2 = Value2 [Section2] KeyWord3 = Value3 KeyWord4 = Value4 

 

 

配置文件由section組成,每個section里面由name=value或者name:value組成,values中的空白符會被移除,在同一個section下的values可以包含該section下的其他values,以格式化字符串的形式表現,或者該values在DEFAULT section中定義過。額外的DEFAULT section可以提供values的初始化,以#開頭的為注釋。

該模塊下有三個類:

ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]])

這是基本的配置類,該類不支持魔術插入。方法如下:

  • RawConfigParser.defaults() 返回一個包含全部實例的字典
  • RawConfigParser.sections() 返回一個包含有效section的列表,DEFAULT不包含在該列表中
  • RawConfigParser.add_section(section)
    增加一個section,如果section存在DuplicateSectionError會被觸發。
  • RawConfigParser.has_section(section) 判斷section是否在配置文件中存在
  • RawConfigParser.options(section) 返回section中可用的options 列表
  • RawConfigParser.has_option(section, option) 判斷section中是否存在options
  • RawConfigParser.read(filenames) 讀入被解析的配置文件
  • RawConfigParser.readfp(fp[, filename]) 讀入並解析配置文件
  • RawConfigParser.get(section, option) 獲取section中option的值
  • RawConfigParser.getint(section, option) 已整形返回option的值
  • RawConfigParser.getfloat(section, option) 同理上面,返回float
  • RawConfigParser.getboolean(section, option)
  • RawConfigParser.items(section) 以列表(name,value)的形式返回section中的每個值
  • RawConfigParser.set(section, option, value)
    如果section存在,則設置該option和value,否則引起NoSectionError.
  • RawConfigParser.write(fileobject) 配置寫入配置文件中
  • RawConfigParser.remove_option(section, option)
    移除section中的option,如果section不存在,引起NoSectionError,移除后返回True,否則返回False
  • RawConfigParser.remove_section(section) 移除section,返回True/False
  • RawConfigParser.optionxform(option)

ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])

該類是RawConfigParser的派生類。支持魔術插入,增加了get和items方法。

  • ConfigParser.get(section, option[, raw[, vars]]) 獲取section中option的值,
  • ConfigParser.items(section[, raw[, vars]]) 返回一個由(name,value)組成的列表對

ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])

該類是ConfigParser的派生類,支持更多的魔術插入。

  • SafeConfigParser.set(section, option, value)
    如果section存在,則設置option的值。value必須是string。
    生成ini配置文件
#!/usr/bin/python import ConfigParser conf=ConfigParser.RawConfigParser() conf.add_section('section1') conf.add_section('section2') conf.set('section1','name1','guol') conf.set('section1','name2','alex') conf.set('section2','name3','polo') conf.set('section2','name4','mark') conffile=open('file.ini','wb') conf.write(conffile) 

 

 

結果如下:
在這里插入圖片描述

解析ini配置文件:

import ConfigParser conf=ConfigParser.RawConfigParser() conf.read('file.ini') if conf.has_section('section2'): print 'Exist section2' if conf.has_option('section2','name3'): print 'section2 has opetion name3, is value' + ' ' +conf.get('section2','name3') 

 

 

結果如下:
在這里插入圖片描述

魔術插入:

import ConfigParser conf1=ConfigParser.ConfigParser() conf1.read('file.ini') conf2=ConfigParser.RawConfigParser() conf2.read('file.ini') print 'Use ConfigParser()' print '''conf1.get('section3','name3',0)''' print conf1.get('section3','name3',0) print '''conf1.get('section3','name3',1)''' print conf1.get('section3','name3',1) print '================================' print 'Use RawConfigParser()' print '''conf2.get('section3','name3')''' print conf2.get('section3','name3') 

 

 

結果如下:
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM