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?
有誰知道爲什麼我現在的代碼不能實現這個目標,以及如何完成它?
請勿使用'is'來比較字符串。它應該工作,如果你使用'如果objname =='停止':'。 –
該死的,我有目的地使用是因爲==在第一次嘗試它時出於某種原因報錯。但現在它可以工作... 謝謝!如果你想要你可以寫一個答案@Rawing,所以我可以給你獎勵你回答.... – Vrankela
你可以打印objname,並檢查它包含什麼,以確保它在某個點。如果你在對象名中有一個空格,那麼你可以嘗試在objename中'停止': –