python解析xml例項

2022-05-02 01:21:10 字數 3047 閱讀 2030

如下,乙個銀行卡打標籤後匯出的資料

(上面的**無法保留格式,還是截張圖吧

**:

1

importos2

import

sys3

import

xml.etree.celementtree as et45

6 from_path = "

./card

" //輸入資料夾

7 to_path = "

./cardout

" //輸出資料夾

8 files =os.listdir(from_path)

9 files.sort() #

按字典序排序

1011

12 i = 1

13for filename in

files:

1415 dir1 =os.path.join(from_path, filename)

16 tree = et.elementtree(file=dir1)

17 root =tree.getroot()

1819 new_filename = filename[:-4] + "

.txt

"20 dir2 =os.path.join(to_path,new_filename)

2122 fobj = open(dir2,'w+'

)2324print("

time: %d, from_filename: %s, to_filename: %s

" %(i, dir1, dir2))

2526

for elem in tree.iterfind('

object/polygon/pt'):

27 fobj.write((elem[0].text + '

,' + elem[1].text + ','

))28

#print(elem[0].text + ',' + elem[1].text + ',')

2930

for elem in tree.iterfind('

object/attributes'):

31fobj.write(elem.text)

3233

fobj.close()

34 i = i + 1

35

效果:

Python例項講解 解析xml

xml xmlversion 1.0 encoding utf 8 info intro 資訊 intro list id 001 head auto userone head name jordy name number 12345678 number age 20 age man hobby 看...

Python中使用SAX解析XML及例項

sax解析xml速度快 占用記憶體小。我們只需要關注三個事件 start element end element char data。如 當sax在解析乙個節點時python 會產生三個事件 2.1start element事件,分別讀取 2.2end element事件,分別讀取 2.3char ...

python sax流式解析xml檔案例項

注 摘出解析xml兩個關鍵函式 import xml.sax import xml.sax.handler class saxhandler xml.sax.contenthandler def init self self.tag none self.attribute defstarteleme...