Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: If file not found try looking for different filename

Tags:

python

file

Problem:

I have code that looks for a file and open it. By default it looks for file that starts with ####### (each # being a number).

Problem is sometimes the file name is ##-##### and other times #####.

I would like a way if the file cannot be found try looking for the other two ways the file could be written.

An IOError exception happens when the file is not found. What I was thinking was to have an except statement that says:

except File2:
    Look for ##### in  myfindFileFunction()
    if file is still not found run except File3
except File3:
    Look for ##-#### in myfindFileFuction()
except:
    print "File not found"

What I am not sure of is how to set up custom exception to work this way, and/or if there is a more pythonic way to do this altogether...

Would setting up a pattern or the three possible file names and iterate thought each until the file is found work better?

like image 991
Tristan Forward Avatar asked Jan 17 '23 00:01

Tristan Forward


1 Answers

Using try/except is indeed a very pythonic (and fast) way of doing things.

You have to weigh not only if it's pythonic, but what impact does that approach has in terms of readability. Will you still understand the code quickly when you look at it again in 6 months? Will somebody else?

I usually make sure that slightly complex try/except clauses to handle this kind of things are well commented. Asides from that... it's a perfectly reasonable way of doing it.

Also, to put your mind at ease regarding performance, a common concern when one is deciding between two approaches, take a look here: Python if vs try-except and you'll see that try/except constructs are fast in Python... really fast.

like image 83
pcalcao Avatar answered Feb 05 '23 09:02

pcalcao