我们正在使用部署在Windows和Linux上的代码存储库-有时在不同的目录中。项目中的一个模块应该如何引用项目中的一个非python资源(CSV文件等)?
如果我们这样做:
thefile = open('test.csv')
or:
thefile = open('../somedirectory/test.csv')
只有当脚本从一个特定目录或目录的一个子集运行时,它才会工作。
我想做的是:
path = getBasePathOfProject() + '/somedirectory/test.csv'
thefile = open(path)
这可能吗?
如果您正在使用安装工具或分发(setup.py安装),那么访问这些打包资源的“正确”方式似乎是使用package_resources。
对你来说,这个例子就是
import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")
当然,是哪个读取了资源,读取的二进制数据是my_data的值
如果你只是需要文件名,你也可以使用
resource_filename(package_or_requirement, resource_name)
例子:
resource_filename("MyPackage","foo.dat")
这样做的好处是,即使它是一个像鸡蛋一样的存档发行版,它也能保证工作。
看到http://packages.python.org/distribute/pkg_resources.html resourcemanager-api