不幸的是,我有一个应用程序不支持 Python 3.7 之后的版本。我有一些代码试图(从 Python 3.12)移植回 Python 3.7,它使用
importlib.resources.files
来获取包中包含的一些非 Python 资源的路径:
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()
Python 3.7 中好像
importlib.resources
没有 files()
。
此代码的 Python 3.7 兼容等效项是什么?
我能够根据
sinoroc 的评论使用
importlib-resources
向后移植来实现此功能。
pip install importlib-resources
然后像这样使用它:
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()
所以实际上唯一的代码更改是用
importlib.resources
查找/替换 importlib_resources
,这只是一个简单的替换。
请注意,PyPi 页面显示此包的 Python >= 3.8,但它似乎在 3.7 上运行良好,至少对于上述用法而言。