首页 > 后端开发 > Python教程 > 如何访问 Python 包内的静态文件?

如何访问 Python 包内的静态文件?

Mary-Kate Olsen
发布: 2024-12-05 09:10:13
原创
781 人浏览过

How Can I Access Static Files Inside a Python Package?

如何访问 Python 包内的静态文件

要读取位于 Python 包内的文件,有以下几种方法可用的方法。一种推荐的方法是利用 Python 3.7 中引入的 importlib.resources 模块。

from importlib import resources
from . import templates

inp_file = resources.files(templates) / 'temp_file'
# open the file using the file-like stream context manager
with inp_file.open("rt") as f:
    template = f.read()
登录后复制

与旧版 pkg_resources 模块相比,此方法具有多种优势。它性能更高,更安全,不需要路径操作,并且仅依赖于标准库。

对于那些使用 3.7 之前的 Python 版本的用户,或者为了向后兼容,可以向后移植 importlib_resources 库。

try:
    from importlib import resources
except ImportError:
    import importlib_resources

from . import templates

inp_file = resources.files(templates) / 'temp_file'
try:
    with inp_file.open("rb") as f:  # or "rt" as text file with universal newlines
        template = f.read()
except AttributeError:
    # Python < PY3.9, fall back to method deprecated in PY3.11.
    template = resources.read_text(templates, 'temp_file')
登录后复制

在此上下文中,resources.files() 函数返回一个 PathLike 对象,该对象表示目标文件的路径。 Resource_name 参数现在表示包内的文件名,没有任何路径分隔符。要访问当前模块中的文件,请指定 __package__ 作为包参数(例如,resources.read_text(__package__, 'temp_file'))。

以上是如何访问 Python 包内的静态文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板