如果在 for 循环中连续出现两个异常,请执行某些操作

BCArg

我正在编写一个 python 脚本,该脚本更改为多个目录并解析这些目录中的不同文件(最终我用解析的数据填充 MySQL 数据库)。实际上,我首先尝试更改为 a/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声明下方做些什么

帕特里克·豪

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")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章