![](/img/trans.png)
[英]How to parse huge XML with Python and XSLT file iteratively and write to CSV
[英]How to write an XML file to a CSV file in Python?
我有一個如下所示的 XML 文件:
<?xml version="1.0"?>
-<Object>
<ID>Object_01</ID>
<Location>Manchester</Location>
<Date>01-01-2020</Date>
<Time>15u59m05s</Time>
-<Max_25Hz>
<25Hz1>0.9166</25Hz>
<25Hz2>0.7979</25Hz>
</Max_25Hz>
-<Max_75Hz>
<75Hz1>1.9659</75Hz>
<75Hz2>1.4831</75Hz>
</Max_75Hz>
</Object>
現在我想將數據寫入一個由制表符分隔的 csv 文件,如下所示:
ID Location Date&Time 25Hz1 25Hz2
Object_01 Manchester 01-01-2020 15:59:05 0.9166 0.7979
請注意,日期和時間在 XML 文件中是分開的,但我需要在 CSV 文件中將它們放在一起。
這是我試過的代碼:
import xml.etree.ElementTree as ET
import csv
root = r'c:\data\FF\Desktop\my_file\XML-files\Object_01.xml'
tree = ET.parse(root)
root = tree.getroot()
headers = ['ID', 'Location','Date&Time','25Hz1','25Hz2']
with open ('new_XML_file.txt', 'w') as f:
writer = csv.writer(f)
for item in root.findall('Object'):
row = []
ID = item.find('Object').find('ID').text
row.append(ID)
location = item.find('Object').find('Location').text
row.append(location)
date = item.find('Object').find('Date').text
time = item.find('Object').find('Location').text
date_time = date+time
row.append(location)
var_25Hz1 = item.find('Max_25Hzt').find('25Hz1').text
row.append(var_25Hz1 )
var_25Hz2 = item.find('Max_25Hz').find('25Hz2').text
row.append(var_25Hz2 )
writer.writerow(headers)
writer.writerow(row)
我只是得到一個空的new_XML_file.txt
,沒有任何錯誤。 誰知道我做錯了什么以及如何解決這個問題?
您示例中的root
是object
,因此當您編寫: for item in root.findall('Object')
您什么也找不到。
嘗試:
for item in root:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.