Python包中的相对文件路径

Ale*_*lex 15 python packages reference relative-path

如何相对于包的目录引用文件?

我的目录结构是:

    /foo
     package1/
      resources/
      __init__.py
     package2/
      resources/
      __init__.py
     script.py

script.py导入包package1package2.虽然可以通过系统上的任何其他脚本导入包.我应该如何引用内部的资源,package1以确保它可以在os.path.curdir任意情况下工作?

Ale*_*ega 16

如果要引用文件foo/package1/resources夹中的文件,则需要使用__file__模块的变量.内部foo/package1/__init__.py:

from os import path
resources_dir = path.join(path.dirname(__file__), 'resources')
Run Code Online (Sandbox Code Playgroud)


jjs*_*jjs 7

一个简单/安全的方法是使用pkg_resources中resource_filename方法(与setuptools一起分发),如下所示:

from pkg_resources import resource_filename
filepath = resource_filename('package1', 'resources/thefile')
Run Code Online (Sandbox Code Playgroud)

或者,如果你在里面实现这个package1/___init___.py:

from pkg_resources import resource_filename
filepath = resource_filename(__name__, 'resources/thefile')
Run Code Online (Sandbox Code Playgroud)

这给你一个干净的解决方案,也是(如果我没有记错)拉链安全.