【发布时间】: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")
我现在有三种可能的结果
-
/baseDirA/the/rest/is/the/same存在:- 然后我
cd到这个目录并执行我想要的操作
- 然后我
-
/baseDirA/the/rest/is/the/same不存在但/baseDirB/the/rest/is/the/same存在:- 我
cd到/baseDirB/the/rest/is/the/same并执行我想要的操作
- 我
-
/baseDirA/the/rest/is/the/same和/baseDirB/the/rest/is/the/same都不存在。- 在这种情况下,使用我当前的
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