zoukankan      html  css  js  c++  java
  • os.path.dirname(__file__)

    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
    复制代码
  • 相关阅读:
    「BJOI2018」治疗之雨
    「NOIP2016」换教室
    「HNOI2015」亚瑟王
    2019/9/15 四校联训
    【AtCoder】 ARC 097
    【AtCoder】 ARC 098
    【AtCoder】 ARC 099
    【AtCoder】 ARC 100
    React:JS中的this和箭头函数
    React:styled-components
  • 原文地址:https://www.cnblogs.com/kenD/p/11135270.html
Copyright © 2011-2022 走看看