I have below code but I want to extract the output to the excel or CSV in python. I would like to export all the data that is printed to the screen, into excel or csv as well, if its not possible
at least ,please show me how to in addition to the above print statement ,add the data to excel or csv file'
import xml.etree.ElementTree as ET
xml = ET.parse('p.xml')
root = xml.getroot()
def getDataRecursive(element):
data = list()
# get attributes of element, necessary for all elements
for key in element.attrib.keys():
data.append(element.tag + '.' + key + ' ' + element.attrib.get(key))
# only end-of-line elements have important text, at least in this example
if len(element) == 0:
if element.text is not None:
data.append(element.tag + ' ' + element.text)
# otherwise, go deeper and add to the current tag
else:
for el in element:
within = getDataRecursive(el)
for data_point in within:
data.append(element.tag + '.' + data_point)
return data
# print results
for x in getDataRecursive(root):
print(x)
'Output looks like this
country.name Liechtenstein
country.rank 1
country.year 2008
country.gdppc 141100
country.neighbor.name Austria
country.neighbor.direction E
country.neighbor.name Switzerland
country.neighbor.direction W
country.name Singapore
country.rank 4
country.year 2011
country.gdppc 59900
country.neighbor.name Malaysia
country.neighbor.direction N
country.name Panama
country.rank 68
country.year 2011
country.gdppc 13600
country.neighbor.name Costa Rica
country.neighbor.direction W
country.neighbor.name Colombia
country.neighbor.direction E'