0, os.path.realpath(file)) 真实文件路径
def TestPrtPwd(self):print("获取当前文件路径——" + os.path.realpath(__file__)) # 获取当前文件路径parent = os.path.dirname(os.path.realpath(__file__))print("获取其父目录——" + parent) # 从当前文件路径中获取目录garder = os.path.dirname(parent)print("获取父目录的父目录——" + garder)print("获取文件名" + os.path.basename(os.path.realpath(__file__))) # 获取文件名# 当前文件的路径pwd = os.getcwd()print("当前运行文件路径" + pwd)# 当前文件的父路径father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".")print("运行文件父路径" + father_path)# 当前文件的前两级目录grader_father = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..")print("运行文件父路径的父路径" + grader_father)return garder
1、sys.argv—- sys.argv[0]是“执行”脚本的名字
sys.argv保存的是脚本的指令参数列表,sys.argv[0]是“执行”脚本的名字。print(sys.argv[0])返回相对路径还是绝对路径,主要看你脚本的执行方式,如下:
#当前路径(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ pwd/Users/schillerxu/Documents/sourcecode/python/numpy_test#代码(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ cat 3.pyimport sysimport osprint(sys.argv)print(sys.argv[0])#两种不同的执行方法对比(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py['3.py']3.py(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py['/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py']/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py
如果获取的是相对路径,可以用os.path.abspath(sys.argv[0])得到绝对路径,用os.path.split()可以得到目录名和文件名,代码如下:
import sysimport ospath=sys.argv[0]abs_path=os.path.abspath(sys.argv[0])dirname,filename=os.path.split(abs_path)print(path)print(abs_path)print(dirname,filename)
程序运行的结果如下:
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ pwd/Users/schillerxu/Documents/sourcecode/python/numpy_test(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py3.py/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py/Users/schillerxu/Documents/sourcecode/python/numpy_test 3.py
最后获得目录名和文件名。
2、 file
file是当前脚本的名字,如果在当前脚本使用, file和sys.argv[0]效果是一样的,比如代码如下:
import sysimport osprint(__file__)
运行结果:
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py3.py(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py
同样受到脚本执行参数的影响。
但是如果脚本互相引用, file和sys.argv[0]结果略有不同,比如代码:
# a.pyimport sysdef f():print(sys.argv[0])print(__file__)
## 3.pyimport sysimport osimport aprint(sys.argv[0])print(__file__)a.f()
执行结果:

可以看到file返回的是被调用(当前)的文件,sys.argv[0]更多的是脚本执行的参数。
3、sys.path
sys.path保存了python解释器的部分路径,可以自己试下,其中sys.path[0]是执行脚本所在的目录。
代码:
import sysimport osprint(sys.path[0])
结果:
$ python 3.py/Users/schillerxu/Documents/sourcecode/python/numpy_test
4、os.getcwd()—工作目录
os.getcwd()返回的是工作目录,并不一定是脚本所在目录。
代码:
import sysimport osprint(os.getcwd())
运行结果:
