在python程序中访问资源的正确方法是什么.
基本上在我的许多python模块中,我最终编写的代码如下:
DIRNAME = os.path.split(__file__)[0]
(...)
template_file = os.path.join(DIRNAME, "template.foo")
Run Code Online (Sandbox Code Playgroud)
哪个好,但是:
在Java中,我有一个完全相同的函数 - 但是当代码位于一堆文件夹中时以及它被打包在.jar文件中时都可以工作.
在Python中是否有这样的功能,或者我可能使用其他任何模式.
std*_*err 17
您将要看看使用或者GET_DATA在STDLIB或通过pkg_resources从setuptools的/分发.您使用哪一个可能取决于您是否已经使用分发将您的代码打包为鸡蛋.
Lau*_*RTE 14
从 Python 3.7 版本开始,访问资源中文件的正确方法是使用importlib.resources库。
例如,可以使用该path函数访问 Python 包中的特定文件:
import importlib.resources
with importlib.resources.path("your.package.templates", "template.foo") as template_file:
...
Run Code Online (Sandbox Code Playgroud)
从 Python 3.9 开始,该包引入了files()API,优于旧版 API。
我们可以使用该files函数来访问 Python 包中的特定文件:
template_res = importlib.resources.files("your.package.templates").joinpath("template.foo")
with importlib.resources.as_file(template_res) as template_file:
...
Run Code Online (Sandbox Code Playgroud)
对于旧版本,我建议安装并使用importlib-resources库。该文档还详细解释了如何使用pkg_resourcesto迁移旧的实现importlib-resources。
| 归档时间: |
|
| 查看次数: |
16447 次 |
| 最近记录: |