I want to load a file from my python module using importlib.resources (see also this question).
If the file is inside a submodule, this is straight forward (run using python -m, see here):
import importlib.resources
from . import submodule
print(importlib.resources.files(submodule).joinpath("file.txt").read_bytes())
For files in the same module, it is possible to use __package__:
import importlib.resources
print(importlib.resources.files(__package__).joinpath("file.txt").read_bytes())
However, I cannot get this approach to work for files inside the top level module, if I want to access them from a submodule:
module
├── file.txt
├── __init__.py
└── submodule
├── __init__.py
└── submodule_script.py
import importlib.resources
from ... import module # ImportError: attempted relative import beyond top-level package
import .. as module # SyntaxError: invalid syntax
from .. import . as module # SyntaxError: invalid syntax
print(importlib.resources.files(module).joinpath("file.txt").read_bytes())
How can I obtain an import-like reference to the top level module location, such that importlib.resources can understand it?
One option is to use an absolute import (import module), but I use relative imports everywhere else in my project and would prefer consistency. Is it possible using relative imports?
.joinpath("..", "file.txt")?import module)?