Pythonic处理多个可能的文件位置的方法?(不使用嵌套的trys)

vic*_*ooi 5 python exception-handling

我有一个需要查找某个文件的Python脚本.

我可以使用os.path.isafile(),但我听说这是糟糕的Python,所以我试图捕获异常.

但是,有两个位置我可以查找该文件.我可以使用嵌套的trys来处理这个:

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')
Run Code Online (Sandbox Code Playgroud)

或者我可以在第一个除了块之外放一个通道,然后在下面再放一个通道:

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')
Run Code Online (Sandbox Code Playgroud)

但是,是否有更多的Pythonic方法来处理上述情况?

干杯,维克多

roo*_*oot 10

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
Run Code Online (Sandbox Code Playgroud)

你也可以else在for循环中添加一个子句; 这是一些代码只有在循环通过耗尽终止时才会执行(没有一个位置有效).