How to refer to data files without hardcoding paths?

Matthew Wilson matt at tplus1.com
Sun Sep 6 02:21:22 CEST 2009


When a python package includes data files like templates or images,
what is the orthodox way of referring to these in code?

I'm working on an application installable through the Python package
index.  Most of the app is just python code, but I use a few jinja2
templates.  Today I realized that I'm hardcoding paths in my app.  They
are relative paths based on os.getcwd(), but at some point, I'll be
running scripts that use this code, these open(...) calls will fail.

I found several posts that talk about using __file__ and then walking
to nearby directories.

I also came across pkg_resources, and that seems to work, but I don't
think I understand it all yet.

Matt




More information about the Python-list mailing list