访问包子目录中的数据 [英] Access data in package subdirectory

查看:79
本文介绍了访问包子目录中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python软件包,其中包含需要打开./data/子目录中的数据文件的模块.现在,我已经将文件的路径硬编码到了我的类和函数中.我想编写更健壮的代码,无论该子目录安装在用户系统上的哪个位置,都可以访问该子目录.

I am writing a python package with modules that need to open data files in a ./data/ subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system.

我尝试了多种方法,但是到目前为止我还没有运气.似乎大多数当前目录"命令返回系统的python解释器的目录,而不是模块的目录.

I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module.

这似乎应该是一个普通的小问题.但是我似乎无法弄清楚.问题的部分原因是我的数据文件不是.py文件,因此我无法使用导入功能等.

This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not .py files, so I can't use import functions and the like.

有什么建议吗?

现在我的软件包目录如下:

Right now my package directory looks like:

/
__init__.py
module1.py
module2.py
data/   
   data.txt

我正在尝试从module*.py访问data.txt

推荐答案

您可以使用__file__来获取程序包的路径,如下所示:

You can use __file__ to get the path to the package, like this:

import os
this_dir, this_filename = os.path.split(__file__)
DATA_PATH = os.path.join(this_dir, "data", "data.txt")
print open(DATA_PATH).read()

这篇关于访问包子目录中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆