我正在编写一个 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")
我现在有三种可能的结果
/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
声明下方做些什么?
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] 删除。
我来说两句