本篇內(nèi)容介紹了“python如何讀取配置文件ini/yaml/xml”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
內(nèi)蒙古網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、自適應(yīng)網(wǎng)站建設(shè)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)成立與2013年到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)。零、前言
python代碼中配置文件是必不可少的內(nèi)容。常見的配置文件格式有很多中:ini、yaml、xml、properties、txt、py等。
一、ini文件
1.1 ini文件的格式
; 注釋內(nèi)容
[url] ; section名稱
baidu = https://www.jb51.net
port = 80[email]
sender = 'xxx@qq.com'
注意section的名稱不可以重復(fù),注釋用分號開頭。
1.2 讀取 configparser
python自帶的configparser模塊可以讀取.ini文件,注意:在python2中是ConfigParser
創(chuàng)建文件的時(shí)候,只需要在pychrame中創(chuàng)建一個(gè)擴(kuò)展名為.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','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)表示層級關(guān)系
縮進(jìn)時(shí)不允許使用Tab,僅允許空格
空格的多少不重要,關(guān)鍵是相同層級的元素要對齊
#表示注釋,#后面的字符都會被忽略
yaml支持的數(shù)據(jù)格式包括:
字典
數(shù)組
純量:單個(gè)的,不可再次分割的值
2.1.2 對象
對象是一組組的鍵值對,使用冒號表示結(jié)構(gòu)
url: https://www.jb51.net log: file_name: test.log backup_count: 5
yaml也允許另外一種寫法,將所有的鍵值對寫成一個(gè)行內(nèi)對象
log: {file_name: test.log, backup_count: 5}
2.1.3 數(shù)組
一組橫線開頭的行,組成一個(gè)數(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允許用兩個(gè)感嘆號表示強(qiáng)制轉(zhuǎn)換
e: !!str 123
f: !!str true
2.1.5 引用
錨點(diǎn)&和別名*,可以用來引用
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
&用來建立錨點(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.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é),多個(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”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
文章名稱:python如何讀取配置文件ini/yaml/xml-創(chuàng)新互聯(lián)
分享地址:http://muchs.cn/article38/deehpp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設(shè)計(jì)公司、網(wǎng)站導(dǎo)航、小程序開發(fā)、自適應(yīng)網(wǎng)站、ChatGPT、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容