1

Suppose I have a small Python package:

/mypack
/mypack/__init__.py
/mypack/mod1.py
/mypack/mod2.py
/mypack/table.csv

If I need something from mod1 in mod2, I can easily do a relative import:

# mod2.py
from .mod2 import something

This package can be copied to and accessed from anywhere and will work right away.

Now suppose I also need that /mypack/table.csv in mod2.

How can I access that file in a way that will work no matter from where I access the module or to where I might copy it?

Two remarks:

  • Without the data file, I just need to copy the folder. I'd like to maintain that capability, instead of using deployment tools. (Because I currently rsync the Python code to several remote computers and just run it there. Not very convenient if more tools would come into play.)
  • There's the option to query the path of a source file with the os package. But this doesn't seem to be fully portable.
Michael
  • 7,407
  • 8
  • 41
  • 84
  • Possible duplicate of [Relative paths in Python](https://stackoverflow.com/questions/918154/relative-paths-in-python) – Aran-Fey Nov 02 '17 at 09:27

1 Answers1

0

From an imported module, the special variable __file__ is the path of the module. It is optional (not defined in an interactive Python session) but it should work in your use case.

So what you need from mod2 module is :

csv_path = os.path.join(dirname(__file__), 'table.csv')

From outside of the module, you could use:

csv_path = os.path.join(dirname(mod2.__file__), 'table.csv')
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252