Python 3.7中importlib.resources.files的兼容等效实现问询
Python 3.7 兼容 importlib.resources.files 的替代实现
Python 3.7 的 importlib.resources 模块没有 files() 和 as_file() 方法,我们可以用该版本原生支持的 API 实现等效功能,以下是两种可行方案:
方案一:贴近原逻辑的路径获取方式
直接替换原代码中的路径获取逻辑,使用 importlib.resources.path()(Python 3.7+ 支持)获取资源的实际文件路径,再读取内容:
import importlib.resources import os def _get_file(filename: str) -> bytes: """given a resource filename, return its contents""" with importlib.resources.path("name.of.my.package", filename) as page_path: with open(page_path, "rb") as f: return f.read()
方案二:更简洁的直接读取方式
如果不需要获取文件路径,只是读取内容,推荐使用 importlib.resources.open_binary() 直接读取资源,省去路径拼接的步骤:
import importlib.resources def _get_file(filename: str) -> bytes: """given a resource filename, return its contents""" with importlib.resources.open_binary("name.of.my.package", filename) as f: return f.read()
注意事项
- 确保资源文件存在于
name.of.my.package包的目录下 - 打包发布时,需在打包配置(如
setup.py的package_data)中声明要包含的资源文件,避免资源丢失
内容的提问来源于stack exchange,提问作者Jason C
相关产品推荐
相关产品推荐

