How to refer to data files without hardcoding paths?

Timothy Madden terminatorul at gmail.com
Sun Sep 6 09:44:38 EDT 2009


Matthew Wilson wrote:
> 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
> 

sys.path[0] should give you the path to your script. By reading the 
documentation I would say it would give the path to the first script 
passed to the interpreter at launch, but after using it I find it also 
gives the current script path inside an imported file. So I use it to 
group the script files in my application into subdirectories, and import 
them as necessary from there.

My app works regardless of the current working directory, and can import 
scripts and load icons from its various subdirectories.

Still I would like to know why it works in imported scripts, since the 
doc page says sys.path[0] is the path to the script that caused the 
interpreter to launch. What would that mean ?


Timothy Madden



More information about the Python-list mailing list