My goal is to load datafiles from an installed Python package using the importlib package. To be fair, this package API seems very complex to use to me and many methods seem to be deprecated. I need to get the absolute path to the data file to provide as input to another program and not do IO directly on the data file.
From what I understood, if I have a package called foo
and a subpackage called foodata
then I can use a context manager to get a path to the file my_file.txt
as follows:
from importlib import resources
from foo import foodata
file_handle = resources.files(foodata)/"my_file.txt"
with resources.as_file(file_handle) as path:
path_to_file = path.as_posix()
# Then do stuff with the path
My directory structure
├── foo
│ ├── foodata
│ │ ├── my_file.txt
However, this code seems way too complex just to get a path to the file and I wonder if there is a simpler way.
My question is: Why a context manager to get a path to a resource? This gets extremely complex especially to access multiple files at once.