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