Similar to the system path, I want to offer some convenience in my code allowing a user to specify a file name that could be in one of a handful of paths.
Say I had two or more config paths
['~/.foo-config/', '/usr/local/myapp/foo-config/']
And my user wants to open bar
, (AKA bar.baz
)
Is there a convenient build in way to let open('bar')
or open('bar.baz')
automatically search these paths for that file in LTR order of precedence? Eg, will temporary adjusting my sys.path
to only be these directories do this for me?
Else, how would you suggest implementing a PATH-like searching open-wrapper?
open
doesn't get into that kind of logic. If you want, write a wrapper function that uses os.path.join
to join each member of sys.path
to the parameter filename, and tries to open them in order, handling the error that occurs when no such file is found.
I'll add that, as another user stated, this is kind of a misuse of sys.path
, but this function would work for any list of paths. Indeed, maybe the nicest option is to use the environment variables suggested by another user to specify a colon-delimited list of config directories, which you then parse and use within your search function.