【发布时间】:2016-11-14 19:37:53
【问题描述】:
(Python 2.7) 下面的代码在目录中搜索 .xml 文件并在每个 XML 中搜索字符串。当 .xml 文件无法找到(或打开)时,我正在尝试获取异常。
到目前为止,当没有找到 XML 时,'with' 语句没有正确执行,但它忽略了 'except IOError' 并继续执行。
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异常,即使except IOError被忽略? -
不,我找不到到达“除了 IOError”的方法
-
可能是文件do存在,但内容为空,所以
for循环不会被执行。原因是您正在过滤 XML 文件,因此很可能会出现这种情况。您可以检查内容是否为空并打印文件名进行测试。 -
在空文件夹上测试这个我没有收到任何输出,所以“我在这里”和“没有找到 xmls”都没有打印出来
-
这是正确的,因为
os.walk找不到任何文件,因此您不应该得到任何输出。你到底想做什么?是否希望在未找到文件或未找到 xml 文件时收到通知?
标签: xml python-2.7 for-loop try-catch except