python內建模組之XML模組

2021-08-23 12:28:15 字數 1404 閱讀 2091

#xml和json 一樣都是可以跨平台的,只是xml相比較,老一點

import xml.etree.elementtree as et

a=et.parse("first_xml.xml")#載入乙個檔案

root=a.getroot()

print(root)#乙個xml檔案

print(root.tag)#xml頭檔名

for i in root:#進入xml檔案中

print(i.attrib)#列印屬性

for j in i:#進入下一層標籤中

print(j.tag,j.text,j.attrib)#j.tag標籤名,j.text值,j,attrib 屬性

# 如果只想呼叫標籤屬性

for x in root.iter('people'):#是把下一層變成字典形式,然後返回

print(x)

print(x.text,x.tag)

#xml檔案的修改

for y in root.iter("people"):

y.set("author","gw")#新增屬性

y1=int(y.text)+1#取值,因為y.text是str模型,所以要轉成int型

y.text=str(y1)#寫入

a.write("first_xml")#寫入乙個檔案,w方式,會覆蓋檔案中的內容,相當於把修改後的檔案取乙個別名

#xml檔案刪除

for c in root.findall("country"):#查詢所有有country的標籤

r=int(c.find("people").text)#取值

print(r)

if r >7:

root.remove(c)

a.write("second_xml")#

下面是從python中生成xml

import xml.etree.elementtree as et

main_xml=et.element("earth")#建立第乙個標籤

one_xml=et.subelement(main_xml,"one_xml",attrib=)#建立第二個標籤,其中attrib代表的是屬性,新增乙個字典的形式進去

people1=et.subelement(one_xml,"people")#建立第三個標籤

people1.text="50"#記住賦值是字串

et=et.elementtree(main_xml)#生成乙個標籤,只需要寫第乙個標籤就行了,因為類似於遞迴,會不斷呼叫下一層

et.write("test.xml",encoding="utf-8",xml_declaration=true)#寫入,其中xml_delaration代表的是最開始的注釋

檔案的方法

Python內建模組 xml模組

處理文件 import xml.etree.elementtree as ettree et.parse xmlfile et.parse 解析xml文件 root tree.getroot 獲取根節點 print root.tag root.tag 獲取根節點標籤 這裡是data print i....

python模組之subprocess模組

import subprocess sh 3.2 ls users egon desktop grep txt mysql.txt tt.txt 事物.txt res1 subprocess.popen ls users jieli desktop shell true,stdout subproc...

python模組之subprocess模組

subprocess意在替代其他幾個老的模組或者函式,比如 os.system os.spawn os.popen popen2.commands.subprocess最簡單的用法就是呼叫shell命令了,另外也可以呼叫程式,並且可以通過stdout,stdin和stderr進行互動。subproc...