python讀取配置文件方式(ini、yaml、xml)
零、前言
python代碼中配置文件是必不可少的內容。常見的配置文件格式有很多中:ini、yaml、xml、properties、txt、py等。
一、ini文件
1.1 ini文件的格式
; 注釋內容
[url] ; section名稱baidu = https://www.jb51.netport = 80
[email]sender = ’xxx@qq.com’
注意section的名稱不可以重復,注釋用分號開頭。
1.2 讀取 configparser
python自帶的configparser模塊可以讀取.ini文件,注意:在python2中是ConfigParser
創建文件的時候,只需要在pychrame中創建一個擴展名為.ini的文件即可。
import configparserfile = ’config.ini’# 創建配置文件對象con = configparser.ConfigParser()# 讀取文件con.read(file, encoding=’utf-8’)# 獲取所有sectionsections = con.sections()# [’url’, ’email’]# 獲取特定sectionitems = con.items(’url’) # 返回結果為元組# [(’baidu’,’https://www.jb51.net’),(’port’, ’80’)] # 數字也默認讀取為字符串# 可以通過dict方法轉換為字典items = dict(items)
二、yaml配置文件
2.1 yaml文件格式
yaml文件是用來方便讀寫的一種格式。它實質上是一種通用的數據串行話格式。
它的基本語法如下:
大小寫敏感
縮進表示層級關系
縮進時不允許使用Tab,僅允許空格
空格的多少不重要,關鍵是相同層級的元素要對齊
#表示注釋,#后面的字符都會被忽略
yaml支持的數據格式包括:
字典數組純量:單個的,不可再次分割的值
2.1.2 對象
對象是一組組的鍵值對,使用冒號表示結構
url: https://www.jb51.netlog: file_name: test.log backup_count: 5
yaml也允許另外一種寫法,將所有的鍵值對寫成一個行內對象
log: {file_name: test.log, backup_count: 5}
2.1.3 數組
一組橫線開頭的行,組成一個數組。
- cat- Dog- Goldfish
轉換成python對象是
[’cat’, ’Dog’, ’Goldfish’]
數組也可以采用行內寫法:
animal: [cat, dog]
轉行成python對象是
{’animal’: [’cat’, ’dog’]}
2.1.4 純量
純量是最基本,不可分割的值。
數字和字符串直接書寫即可:
number: 12.30name: zhangsan
布爾值用true和false表示
isSet: trueflag: false
null用~表示
parent: ~
yaml允許用兩個感嘆號表示強制轉換
e: !!str 123f: !!str true
2.1.5 引用
錨點&和別名*,可以用來引用
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
&用來建立錨點(defaults),<<表示合并到當前數據,*用來引用錨點
下面是另外一個例子:
- &abc st- cat- dog- *abc
轉換成python代碼是:
[’st’, ’cat’, ’dog’, ’st’]
2.2 yaml文件的讀取
讀取yaml文件需要先安裝相應模塊。
pip install yaml
yaml文件內容如下:
url: https://www.baidu.comemail: send: xxx@qq.com port: 25---url: http://www.sina.com.cn
讀取代碼如下:
# coding:utf-8import yaml# 獲取yaml文件路徑yamlPath = ’config.yaml’with open(yamlPath,’rb’) as f: # yaml文件通過---分節,多個節組合成一個列表 date = yaml.safe_load_all(f) # salf_load_all方法得到的是一個迭代器,需要使用list()方法轉換為列表 print(list(date))
三、xml配置文件讀取
xml文件內容如下:
<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')# 打印每部電影的詳細信息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)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: