【问题标题】:Try 'open()', except IOError in Python for loop尝试“open()”,Python for 循环中的 IOError 除外
【发布时间】: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


【解决方案1】:

根据您的 cmets,我认为这就是您要寻找的。​​p>

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2014-05-09
    相关资源
    最近更新 更多