擷取XML資料輸出csv檔
-------------xml
<data>
<row>
<sno>1001</sno>
<sna>大鵬華城</sna>
<tot>38</tot>
<sbi>23</sbi>
<sarea>新店區</sarea>
<mday>20180611071429</mday>
<lat>24.99116</lat>
<lng>121.53398</lng>
<ar>新北市新店區中正路700巷3號</ar>
<sareaen>Xindian Dist.</sareaen>
<snaen>Dapeng Community</snaen>
<aren>No. 3, Lane 700 Chung Cheng Road, Xindian District</aren>
<bemp>15</bemp>
<act>1</act>
</row>
<row>
.
.
.略
import csv
import xml.etree.ElementTree as et
tree=et.ElementTree(file='新北市公共自行車即時資訊.xml') #讀取xml檔
root=tree.getroot() #取得根節點
data=[] #初始化資料表
for i in root:
no=i.find('sno').text
na=i.find('sna').text
ot=i.find('tot').text
#分別找出<sno>,<sna>,<tot>標籤的文字信息
data.append(no+','+na+','+ot)
#新增到list中
#data=['1001,大鵬華城,38', '1002,汐止火車站,56',....]
print(data)
with open('write.csv','w',encoding='utf-8')as file:
rows=csv.writer(file)
for i in data:
rows.writerow([i])
"1001,大鵬華城,38"
"1002,汐止火車站,56"
"1003,汐止區公所,46"
"1004,國泰綜合醫院,56"
"1005,裕隆公園,40"
"1006,捷運大坪林站(3號出口),32"
"1007,汐科火車站(北),34"
標籤: 練習

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁