2016-05-27 61 views
0

我遍历超过5K .xml文件的整个目录,我想只有当它包含标签<name>下字符串“停止”,这本身就是标签<object>的子文件名:为什么我不能在if语句下获得文件名?

import xml.etree.ElementTree as etree 
import os 
path = '/home/devf12/Documents' 
listofnames = [] 

for filename in os.listdir(path): 
    if not filename.endswith('.xml'): continue 
    fullname = os.path.join(path, filename) 
    tree = etree.parse(fullname) 
    root = tree.getroot() 
    objects = [tag for tag in root.findall('object')] 
    for tag in objects: 
     objname = tag.findtext('name') 
     print filename # this is the last place that it will print the filename 
     if objname is 'stop': # but I need to narrow it down if it meets this condition 
      print filename # why wont it print here? 

有谁知道为什么我现在的代码不能实现这个目标,以及如何完成它?

+1

请勿使用'is'来比较字符串。它应该工作,如果你使用'如果objname =='停止':'。 –

+0

该死的,我有目的地使用是因为==在第一次尝试它时出于某种原因报错。但现在它可以工作... 谢谢!如果你想要你可以写一个答案@Rawing,所以我可以给你奖励你回答.... – Vrankela

+0

你可以打印objname,并检查它包含什么,以确保它在某个点。如果你在对象名中有一个空格,那么你可以尝试在objename中'停止': –

回答

2

不要使用is比较字符串,使用==

if objname=='stop': 

is==之间的差异进行了详细的this thread进行了讨论。

相关问题