You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 12:01:00