在CSV文件中,每个字母都有自己的列

时间:2016-05-22 10:18:13

标签: python xml csv

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

我想提取上面这个XML代码的解释,并将其分配给CSV文件中旁边的每个水果(类型)。以下是我的代码。

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

对于print语句,它看起来就像我想要的那样。

Orange, They belong to the Citrus family.
Lemon, They belong to the Lemon family. 

依旧......

但是,在CSV文件中,每个字母都有自己的列。我想在CSV文件的第一列中输入类型,在第二列中输入解释。

Column1    Column2
Orange     They belong to the Citrus family.
Lemon      They belong to the Citrus family.

2 个答案:

答案 0 :(得分:0)

您应该使用writerow,而不是writerows。你应该传递一个列表,而不是字符串。

a.writerow([Type, Explanation])

答案 1 :(得分:-1)

在我(非常有限)的经历中,我发现要写入CSV,您必须将单元格的所需文本放在单独的方括号中,例如:

a.writerow([Type]+[Explanation])

因此它应该在CSV中显示为:

Column 1  Column 2
Type      Explanation

希望这会有所帮助:)