How to use importlib.resources.path(package, resource)?

廉价感情. 提交于 2021-01-27 05:54:42

问题


I'm creating a _GeneratorContextManager with the following code.

try:
    import importlib.resources as pkg_resources
except ImportError:
    # Try backported to PY<37 `importlib_resources`.
    import importlib_resources as pkg_resources
from . import file_resources

package_path= pkg_resources.path(file_resources, "IWNLP.Lemmatizer_20181001.json")

Here is the debugger view of the variable package_path.

Now I want to pass the path of the file "IWNLP.Lemmatizer_20181001.json" to another function:

 lemmatizer = IWNLPWrapper(lemmatizer_path=package_path)

The documentation says "The context manager provides a pathlib.Path object". How can I access the pathlib.Path object?


回答1:


with pkg_resources.path(file_resources, "IWNLP.Lemmatizer_20181001.json") as p:
    package_path = p

p is a variable of type PosixPath and contains the full path to the file IWNLP.Lemmatizer_20181001.json. See https://docs.python.org/3.8/library/pathlib.html#pathlib.Path .



来源:https://stackoverflow.com/questions/58520128/how-to-use-importlib-resources-pathpackage-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!