简体   繁体   English

打开一个相对于python模块路径的文件

[英]Open a file relative to python module path

A little bit of an explanation of my situation before my question.在我提出问题之前对我的情况进行一点解释。

I created a module called foo.我创建了一个名为 foo 的模块。 foo's location in the file system is foo 在文件系统中的位置是

/runtime/foo

and the script "test.py" which imports foo by using sys.path.append() is located in.并且使用 sys.path.append() 导入 foo 的脚本“test.py”位于。

/runtime/bar/test.py

Foo's structure is as follows foo的结构如下

foo
    mtr.txt
    __init__.py
    datasources.py

I would like a class within datasources.py to open the file mtr.txt.我想要 datasources.py 中的一个类来打开文件 mtr.txt。 However, I am not able to do this without explicting giving a path within datasources.但是,如果不明确给出数据源中的路径,我就无法做到这一点。 In this case it would be在这种情况下,它将是

/runtime/foo/mtr.txt

My code will work if I do give it this path, but this is something that should be doable, but I can't find the answer.如果我给它这个路径,我的代码将起作用,但这是应该可行的,但我找不到答案。

I have tried the following commands within a class in datasources.py.我在 datasources.py 的一个类中尝试了以下命令。

open("mtr.txt")
open("./mtr.txt")

and a few other things using the os.path.dirname()以及其他一些使用 os.path.dirname() 的东西

Is there a way to open the file 'mtr.txt' without giving its full path within datasources.py?有没有办法打开文件“mtr.txt”而不在datasources.py中提供其完整路径?

Thanks谢谢

Use pkg_resources使用pkg_resources

import pkg_resources
data = pkg_resources.resource_string(__name__, "mtr.txt")

There are more methods provided by this package, check the docs for Resource Manager API .这个包提供了更多的方法,查看Resource Manager API的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM