os.path.dirname(__file__) 返回脚本的路径
描述:
- 必须实际存在的.py文件,如果直接在命令行执行,则会引发异常NameError: name 'file' is not defined;
- 在运行的时候如果输入完整的执行路径,则返回.py文件的全路径如:/Users/gokaniku/PycharmProjects/qa-autotest/os_path_test.py 则返回/Users/gokaniku/PycharmProjects/qa-autotest,如果os_path_test.py则返回空;
- 结合os.path.abspath()使用效果会好;
实例:
1 import os 2 3 path1 = os.path.dirname(__file__) 4 print (path1) 5 6 path2 = os.path.dirname(os.path.dirname(__file__)) # 7 print(path2)#获取当前运行脚本的绝对路径(去掉最后一个路径) 8 9 path3 = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) 10 print(path3)#获取当前运行脚本的绝对路径(去掉最后2个路径) 11 12 path4 = os.__file__ 13 print(path4)#获取os库的绝对路径 14 15 path5 = os.path.split(os.path.realpath(__file__))[0] 16 print(path5) 17 18 path6 = os.path.join(os.path.split(os.path.realpath(__file__))[0],'os_path_test.py') 19 print(path6)
返回结果:
1 /Users/gokaniku/.pyenv/shims/python3 /Users/gokaniku/PycharmProjects/qa-autotest/os_path_test.py 2 /Users/gokaniku/PycharmProjects/qa-autotest 3 /Users/gokaniku/PycharmProjects 4 /Users/gokaniku/.pyenv/versions/3.7.2/lib/python3.7/os.py 5 /Users/gokaniku/PycharmProjects/qa-autotest 6 /Users/gokaniku/PycharmProjects/qa-autotest/os_path_test.py