python-yml文件讀寫(xiě)與xml文件讀寫(xiě)
一、python-yml文件讀寫(xiě)
使用庫(kù) :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語(yǔ)言的子集。建議用于加載不受信任的輸入。 FullLoader - -加載完整的YAML語(yǔ)言。避免任意代碼執(zhí)行。這是當(dāng)前(PyYAML5.1)默認(rèn)加載器調(diào)用yaml.load(input)(發(fā)出警告后)。 UnsafeLoader - -(也稱(chēng)為L(zhǎng)oader向后兼容性)原始的Loader代碼,可以通過(guò)不受信任的數(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): # 寫(xiě)入數(shù)據(jù): with open(file, "a",encoding='utf-8') as f: # data數(shù)據(jù)中有漢字時(shí),加上: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ù)值后在完整寫(xiě)入。
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文件讀寫(xiě)
使用庫(kù) :import xml
安裝:系統(tǒng)自帶
示例:
如果只是配置文件盡量使用yml來(lái)讀寫(xiě),
讀取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 是一個(gè) Element 物件,代表 XML 的根節(jié)點(diǎn),每一個(gè) Element 物件都有 tag 與 attrib 兩個(gè)屬性:
import xml.etree.ElementTree as ET # 從文件加載并解析 XML 數(shù)據(jù) tree = ET.parse('country_data.xml') root = tree.getroot() print(root.tag) # 打印根節(jié)點(diǎn)名稱(chēng) 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 沒(méi)有屬性所以返回空 country {'name': 'Liechtenstein'} country {'name': 'Singapore'} country {'name': 'Panama'} """
也可以使用索引的方式存取任意的節(jié)點(diǎn),透過(guò) text 屬性即可取得節(jié)點(diǎn)的內(nèi)容:
print(root[0][1].text) """ 2008 """
可透過(guò) 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 會(huì)傳回所有結(jié)果,而 find 則是只傳回第一個(gè)找到的節(jié)點(diǎn):
# 只從第一層子節(jié)點(diǎn)中搜索,傳回所有找到的節(jié)點(diǎn) for country in root.findall('country'): # 只從第一層子節(jié)點(diǎn)中搜索,傳回第一個(gè)找到的節(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ù)可以透過(guò) Element.text 來(lái)修改,而屬性值則可以使用 Element.set() 來(lái)指定,若要將修改的結(jié)果寫(xiě)入 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) # 增加一個(gè) updated 屬性值 rank.set('updated', 'yes') # 寫(xiě)入 XML 文件 tree.write('output.xml')
編輯之后的 XML 文件內(nèi)容會(huì)像這樣:
<?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) # 寫(xiě)入 XML 文件 tree.write('output.xml')
移除節(jié)點(diǎn)之后的 XML 文件內(nèi)容會(huì)像這樣:
<?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)
若要建立一個(gè)全新的 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 可以讓用戶(hù)在 XML 結(jié)構(gòu)中以較復(fù)雜的條件進(jìn)行搜索,以下是一些常見(jià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)中排在第二位的那一個(gè) root.findall(".//neighbor[2]")
XML 排版
若要對(duì)一般的 XML 文件內(nèi)容進(jìn)行自動(dòng)排版,可以使用 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ù)寫(xiě)入文件 root.write("pretty_print.xml", encoding="utf-8")
到此這篇關(guān)于python-yml文件讀寫(xiě)與xml文件讀寫(xiě)的文章就介紹到這了,更多相關(guān) python文件讀寫(xiě)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pandas.DataFrame重置列的行名實(shí)現(xiàn)(set_index)
本文主要介紹了Pandas.DataFrame重置列的行名實(shí)現(xiàn)(set_index),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02python中字典(Dictionary)用法實(shí)例詳解
這篇文章主要介紹了python中字典(Dictionary)用法,以實(shí)例形式較為詳細(xì)的分析了Python字典建立、添加、刪除等常見(jiàn)操作技巧,需要的朋友可以參考下2015-05-05PyTorch實(shí)現(xiàn)圖像識(shí)別實(shí)戰(zhàn)指南
圖像識(shí)別是從給定圖像中提取有意義的信息(例如圖像內(nèi)容)的過(guò)程,下面這篇文章主要給大家介紹了關(guān)于PyTorch實(shí)現(xiàn)圖像識(shí)別的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-02-02Python實(shí)現(xiàn)Word的讀寫(xiě)改操作
本文主要介紹了運(yùn)用docx模塊實(shí)現(xiàn)讀取Word,調(diào)整Word樣式以及Word 寫(xiě)入操作的示例代碼,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-11-11python實(shí)戰(zhàn)之德州撲克第三步-比較大小
這篇文章主要介紹了python實(shí)戰(zhàn)之德州撲克第三步-比較大小,穩(wěn)中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下2021-04-04Python中Django與Echarts的結(jié)合用法圖文詳解
ECharts是一個(gè)第三方控件,下面這篇文章主要給大家介紹了關(guān)于Python中Django與Echarts的結(jié)合用法,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10