尝试 'open()',除了 Python for 循环中的 IOError

Try 'open()', except IOError in Python for loop

(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'

根据您的评论,我想这就是您要找的。

import os

for root, dirs, files in os.walk("/PATH"):
    if not files:
        print 'path ' + root + " has no files"
        continue

    for file1 in files:
        if file1.endswith(".xml") and not file1.startswith("."):
            filePath = os.path.join(root, file1)

            with open(filePath) as f:
                content = f.readlines()

                for a in content:
                    if "string" in a:
                        stringOutput = a.strip()
                        print 'i\'m here' + stringOutput
        else:
            print 'No xmls found, but other files do exists !'