我们正在使用部署在Windows和Linux上的代码存储库-有时在不同的目录中。项目中的一个模块应该如何引用项目中的一个非python资源(CSV文件等)?
如果我们这样做:
thefile = open('test.csv')
or:
thefile = open('../somedirectory/test.csv')
只有当脚本从一个特定目录或目录的一个子集运行时,它才会工作。
我想做的是:
path = getBasePathOfProject() + '/somedirectory/test.csv'
thefile = open(path)
这可能吗?
我经常使用类似的方法:
import os
DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'datadir'))
# if you have more paths to set, you might want to shorten this as
here = lambda x: os.path.abspath(os.path.join(os.path.dirname(__file__), x))
DATA_DIR = here('datadir')
pathjoin = os.path.join
# ...
# later in script
for fn in os.listdir(DATA_DIR):
f = open(pathjoin(DATA_DIR, fn))
# ...
的变量
__file__
保存编写该代码的脚本的文件名,因此可以使路径相对于脚本,但仍然使用绝对路径编写。它运行得非常好,原因如下:
路径是绝对的,但仍然是相对的
项目仍然可以部署在相对容器中
但是你需要注意平台兼容性——Windows操作系统。pathsep与UNIX不同。