使用代码存储库时如何引用资源的相对路径 [英] How to refer to relative paths of resources when working with a code repository
问题描述
我们正在使用一个代码存储库,该代码存储库已部署到Windows和Linux中-有时位于不同的目录中.项目内部的模块之一应如何引用项目中的非Python资源之一(CSV文件等)?
We are working with a code repository which is deployed to both Windows and Linux - sometimes in different directories. How should one of the modules inside the project refer to one of the non-Python resources in the project (CSV files, etc.)?
如果我们做类似的事情:
If we do something like:
thefile=open('test.csv')
或:
thefile=open('../somedirectory/test.csv')
仅当脚本是从一个特定目录或目录的子集运行时才起作用.
It will work only when the script is run from one specific directory, or a subset of the directories.
我想做的事情是这样的:
What I would like to do is something like:
path=getBasePathOfProject()+'/somedirectory/test.csv'
thefile=open(path)
有可能吗?
推荐答案
尝试使用相对于当前文件路径的文件名. "./my_file"的示例:
Try to use a filename relative to the current files path. Example for './my_file':
fn = os.path.join(os.path.dirname(__file__), 'my_file')
在Python 3.4+中,您还可以使用 pathlib :
In Python 3.4+ you can also use pathlib:
fn = pathlib.Path(__file__).parent / 'my_file'
这篇关于使用代码存储库时如何引用资源的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!