Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of handling multiple possible file locations? (Without using nested trys)

I have a Python script that needs to look for a certain file.

I could use os.path.isafile(), but I've heard that's bad Python, so I'm trying to catch the exception instead.

However, there's two locations I could possibly look for the file. I could use nested trys to handle this:

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

Or I could just put a pass in the first except block, and then have another one just below:

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

However, is there a more Pythonic way to handle the above situation?

Cheers, Victor

like image 506
victorhooi Avatar asked Dec 18 '12 07:12

victorhooi


People also ask

Can you have multiple excepts in Python?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do you handle multiple catch blocks for a nested try block explain with an example?

Nested try block is a block in which we can implement one try catch block into another try catch block. The requirement of nested try-catch block arises when an exception occurs in the inner try-catch block is not handled by the inner catch blocks then the outer try-catch blocks are checked for that exception.

Can you open multiple files in Python at once?

Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files.

Can one block of except statements handle multiple exceptions?

Can one block of except statements handle multiple exception? Answer: a Explanation: Each type of exception can be specified directly. There is no need to put it in a list.


1 Answers

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

Also you can add an else clause to the for loop; that is some code is executed only if the loop terminates through exhaustion (none of the locations is valid).

like image 165
root Avatar answered Oct 13 '22 00:10

root