尝试打开()&#39 ;,除了Python for循环中的IOError

时间:2016-07-12 13:55:14

标签: xml python-2.7 for-loop try-catch except

(Python 2.7) 下面的代码在目录中搜索.xml文件并在每个XML中搜索一个字符串。我试图在无法找到(或打开).xml文件时获得异常。

到目前为止,当没有找到XML时,'与'语句没有被正确执行但是它忽略了除了IOError'然后过去了。

-

1 个答案:

答案 0 :(得分:0)

根据您的评论,我认为这正是您所寻找的。

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