【问题标题】:Do something if two exceptions in a row occur in a for loop如果在 for 循环中连续发生两个异常,则执行某些操作
【发布时间】:2019-09-27 13:27:10
【问题描述】:

我正在编写一个 python 脚本,该脚本更改为多个目录并从这些目录中解析不同的文件(最终我用解析的数据填充 MySQL 数据库)。实际上,我首先尝试更改为/baseDirA/the/rest/is/the/same 并解析我想要的表。如果/baseDirA/the/rest/is/the/same 不存在,我尝试更改为/baseDirB/the/rest/is/the/same 并解析可以从/baseDirA/the/rest/is/the/same 解析的相同表。

在我的代码中,这里已经太长了,无法粘贴,我有一个try except 语句,到目前为止,它会打印一条消息以防目录(即/baseDirA/the/rest/is/the/same/baseDirB/the/rest/is/the/same)不存在,如下例所示

import os

# define the two baseDirs
dirs = 'baseDirA baseDirB'.split()

for basedir in dirs:
    try:
        cwd = f"{basedir}/the/rest/is/the/same"
        os.chdir(cwd)
        # Then I am doing the operations to parse different files
        # Below is the except statement, in case one of the directories does not exist
    except FileNotFoundError:
        print(f"WARNING: directory {cwd} does not exist")

我现在有三种可能的结果

  1. /baseDirA/the/rest/is/the/same 存在:

    1. 然后我cd到这个目录并执行我想要的操作
  2. /baseDirA/the/rest/is/the/same 不存在但/baseDirB/the/rest/is/the/same 存在:

    1. cd/baseDirB/the/rest/is/the/same 并执行我想要的操作
  3. /baseDirA/the/rest/is/the/same/baseDirB/the/rest/is/the/same 都不存在。

    1. 在这种情况下,使用我当前的 try except 语句,我会收到如下消息:
WARNING: directory /baseDirA/the/rest/is/the/same does not exist
WARNING: directory /baseDirB/the/rest/is/the/same does not exist

并且,在这种情况下,即如果我执行except 语句连续两次(没有try 语句中的操作),我想执行其他操作。

这样做的最佳方法是什么?最好在我举例说明的循环之前添加另一个for 循环以检查两个目录是否存在?或者我可以在except 语句下面做点什么吗?

【问题讨论】:

  • 计算你的错误并在 count = 2 时做一些事情
  • 只有当我连续出现错误时计数器才会增加?
  • 如果你把它放到 except 块,那么是的。

标签: python-3.x for-loop try-except


【解决方案1】:

如果目录存在,您可以 break 退出 for 循环,并添加一个带有代码的 else 子句,如果循环没有被打破,则将执行:

import os

# define the two baseDirs
dirs = 'baseDirA baseDirB'.split()

for basedir in dirs:
    try:
        cwd = f"{basedir}/the/rest/is/the/same"
        os.chdir(cwd)
        ...
        break
    except FileNotFoundError:
        print(f"WARNING: directory {cwd} does not exist")
else:
    print("No directories existed")

【讨论】:

  • 它完成了这项工作,我现在只是想知道我的文件底部出现了打印语句No directories existed
猜你喜欢
  • 1970-01-01
  • 2022-06-18
  • 1970-01-01
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 2012-05-16
  • 1970-01-01
相关资源
最近更新 更多