0
(Python 2.7版) 下面搜索目錄以.xml文件和搜索代碼每個XML中的字符串。我試圖找出.xml文件無法找到(或打開)時的異常。嘗試「開放()」,除了IO錯誤在Python for循環
到目前爲止,在沒有XML被找到,「用」語句不正確執行,但它無視「除了IO錯誤」,並繼續過去吧。
import os
for root, dirs, files in os.walk('/DIRECTORY PATH HERE'):
for file1 in files:
if file1.endswith(".xml") and not file1.startswith("."):
filePath = os.path.join(root, file1)
try:
with open(filePath) as f:
content = f.readlines()
for a in content:
if "string" in a:
stringOutput = a.strip()
print 'i\'m here' + stringOutput
except IOError:
print 'No xmls found'
即使'IOError'被忽略,你的程序中是否會得到'IOError'異常? – purrogrammer
不,我無法找到前往的道路「除了IO錯誤」 – bzzWomp
這可能是文件*做*存在,但內容是空的,所以'for'循環將不被執行。原因是你正在過濾XML文件,所以這種情況很可能會發生。您可以檢查內容是否爲空並打印文件名以進行測試。 – purrogrammer