Georgios Gousios
Georgios Gousios

Reputation: 2455

Open a file from PYTHONPATH

In a program, and obviously being influenced by the way Java does things, I want to read a static file (a log configuration file, actually) from a directory within the interpreter's PYTHONPATH. I know I could do something like:

import foo
a = foo.__path__
conf = open(a[0] + "/logging.conf")

but I don't know if this is the "Pythonic" way of doing things. How could I distribute the logging configuration file in a way that my application does not need to be externally configured to read it?

Upvotes: 4

Views: 1968

Answers (2)

Joe Futrelle
Joe Futrelle

Reputation: 11

Here's a snippet based on the link Nix posted upthread but written in a more functional style:

def search_path(pathname_suffix):
    cands = [os.path.join(d,pathname_suffix) for d in sys.path]
    try:
        return filter(os.path.exists, cands)[0]
    except IndexError:
        return None

Upvotes: 1

Nicholas Riley
Nicholas Riley

Reputation: 44351

In general, that's fine, though I'm not sure you want a[0] above (that will just give you the first character of the path), and you should use os.path.join instead of just appending / to be cross-platform compatible. You might consider making the path canonical, i.e. os.path.abspath(os.path.dirname(foo.__path__)). Note that it won't work if __path__ is in a zip file or other import trickery is in use, but I wouldn't worry about that (it's not normal to do so for the main program in Python, unlike Java).

If you do want to support zipped files, there's pkg_resources, but that's somewhat deprecated at this point (there's no corresponding API I could see in the new packaging module).

Upvotes: 1

Related Questions