python讀取配置文件方式(ini、yaml、xml)
零、前言
python代碼中配置文件是必不可少的內(nèi)容。常見的配置文件格式有很多中:ini、yaml、xml、properties、txt、py等。
一、ini文件
1.1 ini文件的格式
; 注釋內(nèi)容
[url] ; section名稱baidu = https://www.jb51.netport = 80
[email]sender = ’xxx@qq.com’
注意section的名稱不可以重復(fù),注釋用分號(hào)開頭。
1.2 讀取 configparser
python自帶的configparser模塊可以讀取.ini文件,注意:在python2中是ConfigParser
創(chuàng)建文件的時(shí)候,只需要在pychrame中創(chuàng)建一個(gè)擴(kuò)展名為.ini的文件即可。
import configparserfile = ’config.ini’# 創(chuàng)建配置文件對(duì)象con = configparser.ConfigParser()# 讀取文件con.read(file, encoding=’utf-8’)# 獲取所有sectionsections = con.sections()# [’url’, ’email’]# 獲取特定sectionitems = con.items(’url’) # 返回結(jié)果為元組# [(’baidu’,’https://www.jb51.net’),(’port’, ’80’)] # 數(shù)字也默認(rèn)讀取為字符串# 可以通過dict方法轉(zhuǎn)換為字典items = dict(items)
二、yaml配置文件
2.1 yaml文件格式
yaml文件是用來方便讀寫的一種格式。它實(shí)質(zhì)上是一種通用的數(shù)據(jù)串行話格式。
它的基本語法如下:
大小寫敏感
縮進(jìn)表示層級(jí)關(guān)系
縮進(jìn)時(shí)不允許使用Tab,僅允許空格
空格的多少不重要,關(guān)鍵是相同層級(jí)的元素要對(duì)齊
#表示注釋,#后面的字符都會(huì)被忽略
yaml支持的數(shù)據(jù)格式包括:
字典數(shù)組純量:單個(gè)的,不可再次分割的值
2.1.2 對(duì)象
對(duì)象是一組組的鍵值對(duì),使用冒號(hào)表示結(jié)構(gòu)
url: https://www.jb51.netlog: file_name: test.log backup_count: 5
yaml也允許另外一種寫法,將所有的鍵值對(duì)寫成一個(gè)行內(nèi)對(duì)象
log: {file_name: test.log, backup_count: 5}
2.1.3 數(shù)組
一組橫線開頭的行,組成一個(gè)數(shù)組。
- cat- Dog- Goldfish
轉(zhuǎn)換成python對(duì)象是
[’cat’, ’Dog’, ’Goldfish’]
數(shù)組也可以采用行內(nèi)寫法:
animal: [cat, dog]
轉(zhuǎn)行成python對(duì)象是
{’animal’: [’cat’, ’dog’]}
2.1.4 純量
純量是最基本,不可分割的值。
數(shù)字和字符串直接書寫即可:
number: 12.30name: zhangsan
布爾值用true和false表示
isSet: trueflag: false
null用~表示
parent: ~
yaml允許用兩個(gè)感嘆號(hào)表示強(qiáng)制轉(zhuǎn)換
e: !!str 123f: !!str true
2.1.5 引用
錨點(diǎn)&和別名*,可以用來引用
defaults: &defaults adapter: postgres host: localhost development: databases: myapp_deveploment <<: *defaultstest: databases: myapp_test <<: *defaults
等同于以下代碼
defaults: adapter: postgres host: localhost development: databases: myapp_deveploment adapter: postgres host: localhosttest: databases: myapp_test adapter: postgres host: localhost
&用來建立錨點(diǎn)(defaults),<<表示合并到當(dāng)前數(shù)據(jù),*用來引用錨點(diǎn)
下面是另外一個(gè)例子:
- &abc st- cat- dog- *abc
轉(zhuǎn)換成python代碼是:
[’st’, ’cat’, ’dog’, ’st’]
2.2 yaml文件的讀取
讀取yaml文件需要先安裝相應(yīng)模塊。
pip install yaml
yaml文件內(nèi)容如下:
url: https://www.baidu.comemail: send: xxx@qq.com port: 25---url: http://www.sina.com.cn
讀取代碼如下:
# coding:utf-8import yaml# 獲取yaml文件路徑y(tǒng)amlPath = ’config.yaml’with open(yamlPath,’rb’) as f: # yaml文件通過---分節(jié),多個(gè)節(jié)組合成一個(gè)列表 date = yaml.safe_load_all(f) # salf_load_all方法得到的是一個(gè)迭代器,需要使用list()方法轉(zhuǎn)換為列表 print(list(date))
三、xml配置文件讀取
xml文件內(nèi)容如下:
<collection shelf='New Arrivals'><movie> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description></movie><movie> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description></movie> <movie> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description></movie><movie> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description></movie></collection>
讀取代碼如下:
# coding=utf-8import xml.dom.minidomfrom xml.dom.minidom import parseDOMTree = parse(’config.xml’)collection = DOMTree.documentElementif collection.hasAttribute('shelf'): print('Root element : %s' % collection.getAttribute('shelf'))# 在集合中獲取所有電影movies = collection.getElementsByTagName('movie')# 打印每部電影的詳細(xì)信息for movie in movies: print('*****Movie*****') if movie.hasAttribute('title'): print('Title: %s' % movie.getAttribute('title')) type = movie.getElementsByTagName(’type’)[0] print('Type: %s' % type.childNodes[0].data) format = movie.getElementsByTagName(’format’)[0] print('Format: %s' % format.childNodes[0].data) rating = movie.getElementsByTagName(’rating’)[0] print('Rating: %s' % rating.childNodes[0].data) description = movie.getElementsByTagName(’description’)[0] print('Description: %s' % description.childNodes[0].data)
以上這篇python讀取配置文件方式(ini、yaml、xml)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法2. SpringBoot集成SSM、Dubbo、Redis、JSP的案例小結(jié)及思路講解3. python爬蟲利用代理池更換IP的方法步驟4. JavaScript forEach中return失效問題解決方案5. JS算法題解旋轉(zhuǎn)數(shù)組方法示例6. PHP設(shè)計(jì)模式之迭代器模式Iterator實(shí)例分析【對(duì)象行為型】7. VMware如何進(jìn)入BIOS方法8. python中pandas.read_csv()函數(shù)的深入講解9. Python語言規(guī)范之Pylint的詳細(xì)用法10. springboot用controller跳轉(zhuǎn)html頁面的實(shí)現(xiàn)
