Python Forum

Full Version: where module is loaded from
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a module with some code inside that needs to know what exact file path it was loaded from. another file in the same directory will have some data a feature needs to access.

the use will be to take this path and split the directory path and the base file name, join the directory path with a different base file name, open this different file path, open this different file path, read this different file path, and act on the data contents.

how can the code inside this module find the path of the file it was loaded from, or at least its directory path, preferably without knowing the module name in advance. is there a place to get this information?
(Jul-25-2023, 10:03 PM)Skaperen Wrote: [ -> ]have a module with some code inside that needs to know what exact file path it was loaded from.
Use
__file__
or almost equivalently
__spec__.origin
In order to reliably aggregate data files to a Python package, it is better to use importlib.resources. Also read setuptools' data files support.