简体   繁体   中英

How to write an XML file to a CSV file in Python?

I have an XML file which looks like this:

<?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:

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.

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. 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.

Try:

for item in root:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM