1
我有一个XML
文件看起来像这样:转换XML文件导入CSV
<Organism>
<Name>Bacillus halodurans C-125</Name>
<Enzyme>M.BhaII</Enzyme>
<Motif>GGCC</Motif>
<Enzyme>M1.BhaI</Enzyme>
<Motif>GCATC</Motif>
<Enzyme>M2.BhaI</Enzyme>
<Motif>GCATC</Motif>
</Organism>
<Organism>
<Name>Bacteroides eggerthii 1_2_48FAA</Name>
</Organism>
我试图记录到一个CSV
文件是这样的:
Bacillus halodurans, GGCC
Bacillus halodurans, GCATC
Bacillus halodurans, GCATC
Bacteriodes,
我走近路这是为了创建一个元组列表,它将organism name
和motif
放在一起。我想这使用ElementTree
模块:
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
rebase = tree.getroot()
list = []
for organisms in rebase.findall('Organism'):
name = organisms.find('Name').text
for each_organism in organisms.findall('Motif'):
try:
motif = organisms.find('Motif').text
print name, motif
except AttributeError:
print name
但是输出我得到这个样子的:
Bacillus halodurans, GGCC
Bacillus halodurans, GGCC
Bacillus halodurans, GGCC
只有第一motif
被记录下来。这是我第一次与ElementTree
合作,所以它有点混乱。任何帮助将不胜感激。
我不需要帮助写入CSV
文件。
就像一个魅力。然而,在文件中的某些点上,“生物体”标签下面只有一个“名称”标签。在这种情况下,我得到'AttributeError:'NoneType'对象在'name = organisms.find'('Name')行没有属性'text'的错误。' – Beginner 2014-09-27 20:21:48
@Beginner好吧,我已经更新了回答。据我所知,你想跳过没有名字的生物体 - 因为我在'except'块中使用了'continue'。谢谢。 – alecxe 2014-09-27 20:25:48