How to make an "always relative to current module" file path? How to make an "always relative to current module" file path? python python

How to make an "always relative to current module" file path?


The solution is to use __file__ and it's pretty clean:

import osTEST_FILENAME = os.path.join(os.path.dirname(__file__), 'test.txt')


For normal modules loaded from .py files, the __file__ should be present and usable. To join the information from __file__ onto your relative path, there's a newer option than os.path interfaces available since 2014:

from pathlib import Pathhere = Path(__file__).parentfname = here/'test.txt'with fname.open() as f:    ...

pathlib was added to Python in 3.4 - see PEP428. For users still on Python 2.7 wanting to use the same APIs, a backport is available.

Users interested to apply the most modern approaches available should consider moving to importlib-resources rather than joining data files relative to the source tree. Currently, few users have the luxury of restricting compatibility to Python 3.7+ only, so I mention this as a heads-up to those who like to be at the cutting edge.