python-yml文件讀寫與xml文件讀寫
一、python-yml文件讀寫
使用庫 :import yaml
安裝:
pip install pyyaml
示例:
文件config2.yml
guard_url : 'https://www.xxxx.com' app : chrome_files : 'C:\Program Files\Google\Chrome\Application\chrome.exe' networkTime : 30 title : '公司'
讀取yml數(shù)據(jù)
def read_yml(file):
"""讀取yml,傳入文件路徑file"""
f = open(file,'r',encoding="utf-8") # 讀取文件
yml_config = yaml.load(f,Loader=yaml.FullLoader) # Loader為了更加安全
"""Loader的幾種加載方式
BaseLoader - -僅加載最基本的YAML
SafeLoader - -安全地加載YAML語言的子集。建議用于加載不受信任的輸入。
FullLoader - -加載完整的YAML語言。避免任意代碼執(zhí)行。這是當(dāng)前(PyYAML5.1)默認(rèn)加載器調(diào)用yaml.load(input)(發(fā)出警告后)。
UnsafeLoader - -(也稱為Loader向后兼容性)原始的Loader代碼,可以通過不受信任的數(shù)據(jù)輸入輕松利用。"""
return yml_config打印yml內(nèi)容
yml_info=read_yml('config.yml')
print(yml_info['guard_url'])
print(yml_info['app'])
print((yml_info['app'])['chrome_files'])
"""
https:xxxx.com
{'chrome_files': 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'}
C:\Program Files\Google\Chrome\Application\chrome.exe
"""插入到y(tǒng)ml數(shù)據(jù)
def write_yml(file,data):
# 寫入數(shù)據(jù):
with open(file, "a",encoding='utf-8') as f:
# data數(shù)據(jù)中有漢字時,加上:encoding='utf-8',allow_unicode=True
f.write('\n') # 插入到下一行
yaml.dump(data, f, encoding='utf-8', allow_unicode=True)
data = {"S_data": {"test1": "hello"}, "Sdata2": {"name": "漢字"}}
write_yml('config2.yml',data=data)
更新yml的數(shù)值
邏輯是完整讀取然后更新數(shù)值后在完整寫入。
def read_yml(file):
"""讀取yml,傳入文件路徑file"""
f = open(file, 'r', encoding="utf-8") # 讀取文件
yml_config = yaml.load(f, Loader=yaml.FullLoader) # Loader為了更加安全
return yml_config
def updata_yaml(file):
"""更新yml的數(shù)值"""
old_data=read_yml(file) #讀取文件數(shù)據(jù)
old_data['title']='仔仔大哥哥' #修改讀取的數(shù)據(jù)(
with open(file, "w", encoding="utf-8") as f:
yaml.dump(old_data,f,encoding='utf-8', allow_unicode=True)
updata_yaml('config2.yml')
二、python-xml文件讀寫
使用庫 :import xml
安裝:系統(tǒng)自帶
示例:
如果只是配置文件盡量使用yml來讀寫,
讀取xml文件:
config.xml
<config>
<id>905594711349653</id>
<sec>0tn1jeerioj4x6lcugdd8xmzvm6w42tp</sec>
</config>import xml.dom.minidom
dom = xml.dom.minidom.parse('config.xml')
root = dom.documentElement
def xml(suser):
suser = root.getElementsByTagName(suser)
return suser[0].firstChild.data
id = xml('id') # 進(jìn)程名
print("打印ID:"+id)
"""
打印ID:905594711349653
"""進(jìn)階country_data.xml
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>這里產(chǎn)生的 root 是一個 Element 物件,代表 XML 的根節(jié)點(diǎn),每一個 Element 物件都有 tag 與 attrib 兩個屬性:
import xml.etree.ElementTree as ET
# 從文件加載并解析 XML 數(shù)據(jù)
tree = ET.parse('country_data.xml')
root = tree.getroot()
print(root.tag) # 打印根節(jié)點(diǎn)名稱
print(root.attrib) # 打印根節(jié)點(diǎn)屬性
# for 循環(huán)可以列出所有的子節(jié)點(diǎn):
# 子節(jié)點(diǎn)與屬性
for child in root:
print(child.tag, child.attrib)
"""
data
{} # data 沒有屬性所以返回空
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}
"""
也可以使用索引的方式存取任意的節(jié)點(diǎn),透過 text 屬性即可取得節(jié)點(diǎn)的內(nèi)容:
print(root[0][1].text) """ 2008 """
可透過 get 直接取得指定的屬性值:
# 取得指定的屬性值
print(root[0][3].get('name'))
"""
Austria
"""尋找 XML 節(jié)點(diǎn)
iter 可以在指定節(jié)點(diǎn)之下,以遞回方式搜索所有子節(jié)點(diǎn):
# 搜索所有子節(jié)點(diǎn)
for neighbor in root.iter('neighbor'):
print(neighbor.attrib)
"""
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}
"""findall 與 find 則是只從第一層子節(jié)點(diǎn)中搜索(不包含第二層以下),findall 會傳回所有結(jié)果,而 find 則是只傳回第一個找到的節(jié)點(diǎn):
# 只從第一層子節(jié)點(diǎn)中搜索,傳回所有找到的節(jié)點(diǎn)
for country in root.findall('country'):
# 只從第一層子節(jié)點(diǎn)中搜索,傳回第一個找到的節(jié)點(diǎn)
rank = country.find('rank').text
# 取得節(jié)點(diǎn)指定屬性質(zhì)
name = country.get('name')
print(name, rank)
"""
Liechtenstein 1
Singapore 4
Panama 68
"""修改 XML 數(shù)據(jù)
XML 節(jié)點(diǎn)的數(shù)據(jù)可以透過 Element.text 來修改,而屬性值則可以使用 Element.set() 來指定,若要將修改的結(jié)果寫入 XML 文件,則可使用 ElementTree.write():
# 尋找 rank 節(jié)點(diǎn)
for rank in root.iter('rank'):
# 將 rank 的數(shù)值加 1
new_rank = int(rank.text) + 1
# 設(shè)置新的 rank 值
rank.text = str(new_rank)
# 增加一個 updated 屬性值
rank.set('updated', 'yes')
# 寫入 XML 文件
tree.write('output.xml')編輯之后的 XML 文件內(nèi)容會像這樣:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>若要移除 XML 的節(jié)點(diǎn),可以使用 Element.remove():
# 在第一層子節(jié)點(diǎn)鐘尋找 country 節(jié)點(diǎn)
for country in root.findall('country'):
# 取得 rank 數(shù)值
rank = int(country.find('rank').text)
# 若 rank 大于 50,則移除此節(jié)點(diǎn)
if rank > 50:
root.remove(country)
# 寫入 XML 文件
tree.write('output.xml')移除節(jié)點(diǎn)之后的 XML 文件內(nèi)容會像這樣:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
</data>建立 XML 結(jié)構(gòu)
若要建立一個全新的 XML 結(jié)構(gòu),可以使用 Element 建立根節(jié)點(diǎn),再以 SubElement() 加入子節(jié)點(diǎn):
# 建立新的 XML 結(jié)構(gòu)
orders = ET.Element('orders')
# 新增節(jié)點(diǎn)
order1 = ET.SubElement(orders, 'order')
order1.text = "My Order 1"
order1.set("new", "yes")
# 新增節(jié)點(diǎn)
order2 = ET.SubElement(orders, 'order')
order2.text = "My Order 2"
order2.set("new", "no")
# 輸出 XML 原始數(shù)據(jù)
ET.dump(orders)
<orders><order new="yes">My Order 1</order><order new="no">My Order 2</order></orders>XPath 搜索
XPath 可以讓用戶在 XML 結(jié)構(gòu)中以較復(fù)雜的條件進(jìn)行搜索,以下是一些常見的范例。
# 頂層節(jié)點(diǎn)
root.findall(".")
# 尋找「頂層節(jié)點(diǎn) => country => neighbor」這樣結(jié)構(gòu)的節(jié)點(diǎn)
root.findall("./country/neighbor")
# 尋找 name 屬性為 Singapore,且含有 year 子節(jié)點(diǎn)的節(jié)點(diǎn)
root.findall(".//year/..[@name='Singapore']")
# 尋找父節(jié)點(diǎn) name 屬性為 Singapore 的 year 節(jié)點(diǎn)
root.findall(".//*[@name='Singapore']/year")
# 尋找在同一層 neighbor 節(jié)點(diǎn)中排在第二位的那一個
root.findall(".//neighbor[2]")XML 排版
若要對一般的 XML 文件內(nèi)容進(jìn)行自動排版,可以使用 lxml 模組的 etree:
import lxml.etree as etree
# 讀取 XML 文件
root = etree.parse("country_data.xml")
# 輸出排版的 XML 數(shù)據(jù)
print(etree.tostring(root, pretty_print=True, encoding="unicode"))
# 將排版的 XML 數(shù)據(jù)寫入文件
root.write("pretty_print.xml", encoding="utf-8")到此這篇關(guān)于python-yml文件讀寫與xml文件讀寫的文章就介紹到這了,更多相關(guān) python文件讀寫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?遞歸式實(shí)現(xiàn)二叉樹前序,中序,后序遍歷
這篇文章主要介紹了Python?遞歸式實(shí)現(xiàn)二叉樹前序,中序,后序遍歷,更多相關(guān)資料,需要的小伙伴可以參考下面具體的文章內(nèi)容2022-03-03
Pytorch?和?Tensorflow?v1?兼容的環(huán)境搭建方法
這篇文章主要介紹了搭建Pytorch?和?Tensorflow?v1?兼容的環(huán)境,本文是小編經(jīng)過多次實(shí)踐得到的環(huán)境配置教程,給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-11-11
詳解Python實(shí)現(xiàn)進(jìn)度條的4種方式
這篇文章主要介紹了Python實(shí)現(xiàn)進(jìn)度條的4種方式,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01
Python串口通信的接收與發(fā)送的實(shí)現(xiàn)
串口通信是指通過串口進(jìn)行數(shù)據(jù)傳輸?shù)囊环N通信方式,本文就來介紹一下Python串口通信的接收與發(fā)送的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11
python中小數(shù)點(diǎn)后取2位(四舍五入)及取2位(四舍五不入)的方法
這篇文章主要給大家介紹了python中小數(shù)點(diǎn)后取2位(四舍五入)及取2位(四舍五不入)的方法,在Python中取兩位小數(shù)的方法其實(shí)非常簡單,需要的朋友可以參考下2023-08-08
python數(shù)據(jù)寫入Excel文件中的實(shí)現(xiàn)步驟
Python作為時下流行的語言,數(shù)據(jù)寫入Excel是必要的操作,下面這篇文章主要給大家介紹了關(guān)于python數(shù)據(jù)寫入Excel文件中的簡單實(shí)現(xiàn)方法,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
關(guān)于自動化測試框架pytest的Fixture固件
這篇文章主要介紹了關(guān)于自動化測試框架pytest的Fixture固件,Fixture它其實(shí)就是一些函數(shù),會在執(zhí)行測試方法/測試函數(shù)前后加載運(yùn)行它們,需要的朋友可以參考下2023-03-03

