处理多个可能文件位置的Python方式?(不使用嵌套try)
我有一个Python脚本,需要查找某个文件 我可以使用os.path.isafile(),但我听说这是糟糕的Python,所以我尝试捕获异常 但是,我可以在两个位置查找该文件。我可以使用嵌套的try来处理此问题:处理多个可能文件位置的Python方式?(不使用嵌套try),python,exception-handling,Python,Exception Handling,我有一个Python脚本,需要查找某个文件 我可以使用os.path.isafile(),但我听说这是糟糕的Python,所以我尝试捕获异常 但是,我可以在两个位置查找该文件。我可以使用嵌套的try来处理此问题: try: keyfile = 'location1' try_to_connect(keyfile) except IOError: try: keyfile = 'location2' try_to_connect(keyfil
try:
keyfile = 'location1'
try_to_connect(keyfile)
except IOError:
try:
keyfile = 'location2'
try_to_connect(keyfile)
except:
logger.error('Keyfile not found at either location1 or location2')
或者我可以在第一个街区放一个通行证,然后在下面再放一个:
try:
keyfile = 'location1'
try_to_connect(keyfile)
except IOError:
pass
try:
keyfile = 'location2'
try_to_connect(keyfile)
except:
logger.error('Keyfile not found at either location1 or location2')
然而,有没有一种更像蟒蛇的方式来处理上述情况
干杯,
胜利者
您还可以向for循环添加
else
子句;也就是说,只有当循环因耗尽而终止时(所有位置都无效),才会执行某些代码。为什么不编写一个循环-1因为不知道循环的概念,这是一个非常有效的问题,需要一个更具python风格的方法来做到这一点。我真的不认为你可以因为他没有考虑循环而责骂他。我会在for
块中添加else:
,并显示错误消息,没有一个位置匹配。+1。此外,您可能希望将其封装在函数中,尝试连接(位置)
(尽管可能使用更好的名称…)。
for location in locations:
try:
try_to_connect(location)
break
except IOError:
continue
else:
# this else is optional
# executes some code if none of the locations is valid
# for example raise an Error as suggested @eumiro