python讀取配置文件方式(ini、yaml、xml)
零、前言
python代碼中配置文件是必不可少的內(nèi)容。常見的配置文件格式有很多中:ini、yaml、xml、properties、txt、py等。
一、ini文件
1.1 ini文件的格式
; 注釋內(nèi)容
[url] ; section名稱
baidu = http://www.dbjr.com.cn
port = 80[email]
sender = 'xxx@qq.com'
注意section的名稱不可以重復(fù),注釋用分號開頭。
1.2 讀取 configparser
python自帶的configparser模塊可以讀取.ini文件,注意:在python2中是ConfigParser
創(chuàng)建文件的時候,只需要在pychrame中創(chuàng)建一個擴展名為.ini的文件即可。
import configparser file = 'config.ini' # 創(chuàng)建配置文件對象 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)讀取為字符串 # 可以通過dict方法轉(zhuǎn)換為字典 items = dict(items)
二、yaml配置文件
2.1 yaml文件格式
yaml文件是用來方便讀寫的一種格式。它實質(zhì)上是一種通用的數(shù)據(jù)串行話格式。
它的基本語法如下:
大小寫敏感
縮進表示層級關(guān)系
縮進時不允許使用Tab,僅允許空格
空格的多少不重要,關(guān)鍵是相同層級的元素要對齊
#表示注釋,#后面的字符都會被忽略
yaml支持的數(shù)據(jù)格式包括:
字典
數(shù)組
純量:單個的,不可再次分割的值
2.1.2 對象
對象是一組組的鍵值對,使用冒號表示結(jié)構(gòu)
url: http://www.dbjr.com.cn log: file_name: test.log backup_count: 5
yaml也允許另外一種寫法,將所有的鍵值對寫成一個行內(nèi)對象
log: {file_name: test.log, backup_count: 5}
2.1.3 數(shù)組
一組橫線開頭的行,組成一個數(shù)組。
- cat
- Dog
- Goldfish
轉(zhuǎn)換成python對象是
['cat', 'Dog', 'Goldfish']
數(shù)組也可以采用行內(nèi)寫法:
animal: [cat, dog]
轉(zhuǎn)行成python對象是
{'animal': ['cat', 'dog']}
2.1.4 純量
純量是最基本,不可分割的值。
數(shù)字和字符串直接書寫即可:
number: 12.30
name: zhangsan
布爾值用true和false表示
isSet: true
flag: false
null用~表示
parent: ~
yaml允許用兩個感嘆號表示強制轉(zhuǎn)換
e: !!str 123
f: !!str true
2.1.5 引用
錨點&和別名*,可以用來引用
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
&用來建立錨點(defaults),<<表示合并到當(dāng)前數(shù)據(jù),*用來引用錨點
下面是另外一個例子:
- &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文件通過---分節(jié),多個節(jié)組合成一個列表 date = yaml.safe_load_all(f) # salf_load_all方法得到的是一個迭代器,需要使用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") # 打印每部電影的詳細信息 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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
TensorFlow高效讀取數(shù)據(jù)的方法示例
這篇文章主要介紹了TensorFlow高效讀取數(shù)據(jù)的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02關(guān)于pyinstaller?打包多個py文件的問題
這篇文章主要介紹了pyinstaller?打包多個py文件及遇到的問題,本文通過實例代碼給大家詳細介紹,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10python3+PyQt5使用數(shù)據(jù)庫表視圖
這篇文章主要為大家詳細介紹了python3+PyQt5使用數(shù)據(jù)庫表視圖,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04