脚本所在的路径

If you mean the directory of the script being run:

import os
os.path.dirname(os.path.abspath(__file__))

注意:__file__ 只有在直接运行脚本的时候才会有

当前的工作路径

If you mean the current working directory:

import os
os.getcwd()

当前的工作路径和文件的路径显然是可以不一样的,比如可以 $ python foo/bar.py,那么 os.getcwd()xxx 的话,os.path.dirname(os.path.abspath(__file__)) 的结果就是 xxx/foo/

如果是 open(filename, \'r\'),这时候的 filename 可以是 /foo/bar.txt 这样的绝对路径,或者是 foo/bar.txt 这样的相对路径,绝对路径无悬念,记住相对路径是相对于当前工作路径的。所以在代码中写死 open(\'foo.txt\', \'r\') 的话可能会因为执行时候的实际 cwd 变化而导致错误。

sys.argv

sys.argv[0] 其实就是当前脚本的位置。再往后的每一项就是执行这个文件的时候附带的各个参数(如果有的话)。

参考

filesystems – How to get full path of current file\’s directory in Python? – Stack Overflow