Jacob Lyles Jacob Lyles - 5 months ago 32
Python Question

Python Access Data in Package Subdirectory

I am writing a python package with modules that need to open data files in a

./data/
subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system.

I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module.

This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not
.py
files, so I can't use import functions and the like.

Any suggestions?

Right now my package directory looks like:

/
__init__.py
module1.py
module2.py
data/
data.txt


I am trying to access
data.txt
from
module*.py


Thanks!

Answer

You can use underscore-underscore-file-underscore-underscore (__file__) to get the path to the package, like this:

import os
this_dir, this_filename = os.path.split(__file__)
DATA_PATH = os.path.join(this_dir, "data", "data.txt")
print open(DATA_PATH).read()
Comments