<Fruits>
<Fruit>
<Family>Citrus</Family>
<Explanation>They belong to the Citrus.</Explanation>
<Type>Orange</Type>
<Type>Lemon</Type>
<Type>Lime</Type>
<Type>Grapefruit</Type>
</Fruit>
<Fruit>
<Family>Pomes</Family>
<Explanation>it belongs to the Pomes. Pomes are composed of one or more carpels, surrounded by accessory tissue.</Explanation>
<Type>Apple</Type>
<Type>Pear</Type>
</Fruit>
I want to extract the Explanation of this XML code above, and assign it to each fruit(Type) next to it in a CSV file. Here is my code below.
import os, csv
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")
with open('test.csv','w') as fp:
a = csv.writer(fp, delimiter=',')
for f in Fruit:
Explanation = f.find("Explanation").text
Types = f.findall("Type")
for t in Types:
Type = t.text
print ("{0}, {1}".format(Type, Explanation))
a.writerows("{0}, {1}".format(Type, Explanation))
For the print statement it appears exactly the way I want it.
Orange, They belong to the Citrus family.
Lemon, They belong to the Lemon family.
and so on...
However, in the CSV file each letter has its own column. I would like to have the type in the first column in the CSV file and in the second column the Explanation.
Column1 Column2
Orange They belong to the Citrus family.
Lemon They belong to the Citrus family.
You should use writerow
, not writerows
. And you should pass it a list, not a string.
a.writerow([Type, Explanation])
In my (very limited) experience, I have found that for writing to CSVs, you have to put the desired text for the cells in separate square brackets, for example:
a.writerow([Type]+[Explanation])
So it should appear in the CSV as:
Column 1 Column 2
Type Explanation
Hope this helps :)
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.