为什么我无法在if语句下获取文件名?

时间:2016-05-27 07:50:21

标签: python xml xml-parsing

我正在使用超过5k .xml文件遍历整个目录,只有当文件名包含字符串&#39; stop&#39;标记<name>下的标记<object>

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 个答案:

答案 0 :(得分:2)

请勿使用is来比较字符串,请使用==

if objname=='stop':

is==之间的差异已在this thread中详细讨论。