I have an application that unfortunately does not support Python past 3.7. I have some code I'm trying to port (from Python 3.12) back to Python 3.7 that uses importlib.resources.files
to get the path to some non-Python resources that are included in the package:
def _get_file (filename: str) -> bytes:
"""given a resource filename, return its contents"""
res_path = importlib.resources.files("name.of.my.package")
with importlib.resources.as_file(res_path) as the_path:
page_path = os.path.join(the_path, filename)
with open(page_path, "rb") as f:
return f.read()
It seems like importlib.resources
doesn't have a files()
in Python 3.7.
What is the Python 3.7 compatible equivalent of this code?
I was able to get this working with the importlib-resources
backport as per sinoroc's comment.
pip install importlib-resources
And then using it like:
import importlib_resources
def _get_file (filename: str) -> bytes:
"""given a resource filename, return its contents"""
res_path = importlib_resources.files("name.of.my.package")
with importlib_resources.as_file(res_path) as the_path:
page_path = os.path.join(the_path, filename)
with open(page_path, "rb") as f:
return f.read()
So really the only code change was find/replacing importlib.resources
with importlib_resources
, it's just a drop-in replacement.
Note the PyPi page says Python >= 3.8 for this package, but it seems to work fine on 3.7, at least for the above usage.