[英]How to write an XML file to a CSV file in Python?
I have an XML file which looks like this:我有一个如下所示的 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>
Now I would like to write the data to a csv file which is tab separated and looks like this:现在我想将数据写入一个由制表符分隔的 csv 文件,如下所示:
ID Location Date&Time 25Hz1 25Hz2
Object_01 Manchester 01-01-2020 15:59:05 0.9166 0.7979
Please note that the date & time are separated in the XML file but I need them together in the CSV file.请注意,日期和时间在 XML 文件中是分开的,但我需要在 CSV 文件中将它们放在一起。
This is the code I tried:这是我试过的代码:
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)
I just get an empty new_XML_file.txt
back, no errors nothing.我只是得到一个空的new_XML_file.txt
,没有任何错误。 Who knows what I'm doing wrong and how I can fix this?谁知道我做错了什么以及如何解决这个问题?
The root
in your example is object
, so when you write: for item in root.findall('Object')
you find nothing.您示例中的root
是object
,因此当您编写: for item in root.findall('Object')
您什么也找不到。
Try:尝试:
for item in root:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.