python讀取配置文件方式(ini、yaml、xml)
零、前言
python代碼中配置文件是必不可少的內(nèi)容。常見(jiàn)的配置文件格式有很多中:ini、yaml、xml、properties、txt、py等。
一、ini文件
1.1 ini文件的格式
; 注釋內(nèi)容
[url] ; section名稱(chēng)
baidu = http://www.dbjr.com.cn
port = 80[email]
sender = 'xxx@qq.com'
注意section的名稱(chēng)不可以重復(fù),注釋用分號(hào)開(kāi)頭。
1.2 讀取 configparser
python自帶的configparser模塊可以讀取.ini文件,注意:在python2中是ConfigParser
創(chuàng)建文件的時(shí)候,只需要在pychrame中創(chuàng)建一個(gè)擴(kuò)展名為.ini的文件即可。
import configparser file = 'config.ini' # 創(chuàng)建配置文件對(duì)象 con = configparser.ConfigParser() # 讀取文件 con.read(file, encoding='utf-8') # 獲取所有section sections = con.sections() # ['url', 'email'] # 獲取特定section items = con.items('url') # 返回結(jié)果為元組 # [('baidu','http://www.dbjr.com.cn'),('port', '80')] # 數(shù)字也默認(rèn)讀取為字符串 # 可以通過(guò)dict方法轉(zhuǎn)換為字典 items = dict(items)
二、yaml配置文件
2.1 yaml文件格式
yaml文件是用來(lái)方便讀寫(xiě)的一種格式。它實(shí)質(zhì)上是一種通用的數(shù)據(jù)串行話(huà)格式。
它的基本語(yǔ)法如下:
大小寫(xiě)敏感
縮進(jìn)表示層級(jí)關(guān)系
縮進(jìn)時(shí)不允許使用Tab,僅允許空格
空格的多少不重要,關(guān)鍵是相同層級(jí)的元素要對(duì)齊
#表示注釋?zhuān)?后面的字符都會(huì)被忽略
yaml支持的數(shù)據(jù)格式包括:
字典
數(shù)組
純量:?jiǎn)蝹€(gè)的,不可再次分割的值
2.1.2 對(duì)象
對(duì)象是一組組的鍵值對(duì),使用冒號(hào)表示結(jié)構(gòu)
url: http://www.dbjr.com.cn log: file_name: test.log backup_count: 5
yaml也允許另外一種寫(xiě)法,將所有的鍵值對(duì)寫(xiě)成一個(gè)行內(nèi)對(duì)象
log: {file_name: test.log, backup_count: 5}
2.1.3 數(shù)組
一組橫線(xiàn)開(kāi)頭的行,組成一個(gè)數(shù)組。
- cat
- Dog
- Goldfish
轉(zhuǎn)換成python對(duì)象是
['cat', 'Dog', 'Goldfish']
數(shù)組也可以采用行內(nèi)寫(xiě)法:
animal: [cat, dog]
轉(zhuǎn)行成python對(duì)象是
{'animal': ['cat', 'dog']}
2.1.4 純量
純量是最基本,不可分割的值。
數(shù)字和字符串直接書(shū)寫(xiě)即可:
number: 12.30
name: zhangsan
布爾值用true和false表示
isSet: true
flag: false
null用~表示
parent: ~
yaml允許用兩個(gè)感嘆號(hào)表示強(qiáng)制轉(zhuǎn)換
e: !!str 123
f: !!str true
2.1.5 引用
錨點(diǎn)&和別名*,可以用來(lái)引用
defaults: &defaults adapter: postgres host: localhost development: databases: myapp_deveploment <<: *defaults test: databases: myapp_test <<: *defaults
等同于以下代碼
defaults: adapter: postgres host: localhost development: databases: myapp_deveploment adapter: postgres host: localhost test: databases: myapp_test adapter: postgres host: localhost
&用來(lái)建立錨點(diǎn)(defaults),<<表示合并到當(dāng)前數(shù)據(jù),*用來(lái)引用錨點(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.com email: send: xxx@qq.com port: 25 --- url: http://www.sina.com.cn
讀取代碼如下:
# coding:utf-8 import yaml # 獲取yaml文件路徑 yamlPath = 'config.yaml' with open(yamlPath,'rb') as f: # yaml文件通過(guò)---分節(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 title="Enemy Behind"> <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 title="Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title="Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection>
讀取代碼如下:
# coding=utf-8 import xml.dom.minidom from xml.dom.minidom import parse DOMTree = parse('config.xml') collection = DOMTree.documentElement if 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)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
TensorFlow高效讀取數(shù)據(jù)的方法示例
這篇文章主要介紹了TensorFlow高效讀取數(shù)據(jù)的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02關(guān)于pyinstaller?打包多個(gè)py文件的問(wèn)題
這篇文章主要介紹了pyinstaller?打包多個(gè)py文件及遇到的問(wèn)題,本文通過(guò)實(shí)例代碼給大家詳細(xì)介紹,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10python3+PyQt5使用數(shù)據(jù)庫(kù)表視圖
這篇文章主要為大家詳細(xì)介紹了python3+PyQt5使用數(shù)據(jù)庫(kù)表視圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04python析構(gòu)函數(shù)用法及注意事項(xiàng)
在本篇文章里小編給大家整理的是一篇關(guān)于python析構(gòu)函數(shù)用法及注意事項(xiàng),有需要的朋友們可以學(xué)習(xí)參考下。2021-06-06