5

I have some python code where I can accept two different file names, so I would like to do something like try the first file name, if there is an exception then try the second filename, if the second try fails, then raise the exception and handle the error.

So the basic logic is:

first try this: f = file(name1) if not, then try this f = file(name2) else error() 

I'm pretty sure I could do this with nested try/except blocks, but that doesn't seem like a good solution. Also, if I want to scale up to something like 20 different filenames, then nesting the try/except blocks would get really messy.

Thanks!

1

2 Answers 2

19

You could simply use a for loop:

for name in filenames: try: f = open(name) break except IOError: pass else: # error 
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent solution, and a very good example for a useful application of an else clause in a for loop! I need to remember this.
I like this solution especially because it trivially scales to more than just two files.
Well, that's basically the question I was asking.
5

You can do a loop of try ... except like:

for f_name in names: try: f = open(f_name, 'r') # do something break # Exit from the loop if you reached this point except: print 'error, going to try the next one' 

1 Comment

I don't understand why this was downvoted, it's the same solution as the other one and it posted within a minute of the other one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.