如何安全地访问与 python 模块捆绑的数据文件?

发布于 2024-12-19 02:28:13 字数 153 浏览 4 评论 0原文

假设我的 python 包中包含相同的数据文件。

据我所知,distils 不建议使用 __file__ ,因为如果您的模块位于 Egg 文件内,您将无法获得有效路径。

现在,我应该使用哪种方法才能读取这些文件(在鸡蛋内部还是外部)?

Let's say that I do have same data files that are included in my python package.

I understand that the usage of __file__ is not recommended by distils because you will not be able to get a valid path if your module is inside an egg file.

Now, which method should I use in oder to be able to read these files, being inside eggs or outside them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千と千尋 2024-12-26 02:28:13

使用评论中链接的其他问题,我得到了一个非常适合 Python 2.6+ 的解决方案。特别是,在我自己的模块中,我同时拥有代码和数据文件,如下所示:

mymod/
|
| __init__.py
| code.py
| data.dat

为了访问 code.py 中的 data.dat,我这样做了:

import pkgutil
def get_data():
    return pkgutil.get_data('', 'data.dat')

Using the other question linked in the comments, I got a solution that works pretty well for Python 2.6+. In particular, in my own module, I have both code and data files like so:

mymod/
|
| __init__.py
| code.py
| data.dat

To get access to data.dat in code.py, I did this:

import pkgutil
def get_data():
    return pkgutil.get_data('', 'data.dat')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文