Jacob Lyles Jacob Lyles - 1 year ago 114
Python Question

Python Access Data in Package Subdirectory

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

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
files, so I can't use import functions and the like.

Any suggestions?

Right now my package directory looks like:


I am trying to access


Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download