Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I create a relative path to a file?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.

How do you assign a path to a Python module?

So, to ensure that your module is found, you need to do one of the following: Put mod.py in the directory where the input script is located, or the current directory if interactive. Modify the PYTHONPATH environment variable to contain the directory where mod.py is located before starting the interpreter.

What does __ file __ mean in Python?

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.


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

import os

TEST_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 Path

here = Path(__file__).parent
fname = 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.