如果您正在寻找一种方法来访问已安装模块中的非Python数据文件,就像您链接的问题一样(顶级包中的配置文件应该可以在子包中访问),请使用pkg_resources
机器而不是发明自定义路径解析。项目结构示例:
project
├── setup.py
└── root
├── __init__.py
├── config.txt
├── sub1
│ └── __init__.py
└── sub2
└── __init__.py
setup.py
:
from setuptools import setup
setup(
name='myproj',
...,
packages=['root', 'root.sub1', 'root.sub2'], # or setuptools.find_packages()
package_data={'root': ['config.txt']}
)
Update:
正如所指出的wim https://stackoverflow.com/users/674039/wim在评论中,现在有一个向后移植importlib.resources https://docs.python.org/3.7/library/importlib.html#module-importlib.resources(仅适用于 Python 3.7 及更高版本)-importlib_resources https://importlib-resources.readthedocs.io/en/latest/,它提供了一种利用现代资源机械pathlib
:
# access the filepath
importlib_resources.path('root', 'config.txt')
# access the contents as string
importlib_resources.read_text('root', 'config.txt')
# access the contents as file-like object
importlib_resources.open_binary('root', 'config.txt')
原答案
Using pkg_resources https://setuptools.readthedocs.io/en/latest/pkg_resources.html,您可以访问root/config.txt
从包的任何位置,无需执行任何路径解析:
import pkg_resources
# access the filepath:
filepath = pkg_resources.resource_filename('root', 'config.txt')
# access the contents as string:
contents = pkg_resources.resource_string('root', 'config.txt')
# access the contents as file-like object:
contents = pkg_resources.resource_stream('root', 'config.txt')
etc.