How to refer to relative paths of resources when w

2019-01-03 20:07发布

We are working with a code repository which is deployed both to Windows and Linux - sometimes on 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')

or:

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)

Is this the right way? Is it possible?

7条回答
霸刀☆藐视天下
2楼-- · 2019-01-03 21:11

In Python, paths are relative to the current working directory, which in most cases is the directory from which you run your program. The current working directory is very likely not as same as the directory of your module file, so using a path relative to your current module file is always a bad choice.

Using absolute path should be the best solution:

import os
package_dir = os.path.dirname(os.path.abspath(__file__))
thefile = os.path.join(package_dir,'test.cvs')
查看更多
登录 后发表回答