Python 3.7 相当于 `importlib.resources.files`

问题描述 投票:0回答:1

不幸的是,我有一个应用程序不支持 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 兼容等效项是什么?

python python-3.7 python-importlib
1个回答
1
投票

我能够根据

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 上运行良好,至少对于上述用法而言。

© www.soinside.com 2019 - 2024. All rights reserved.