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
    复制代码
  • 相关阅读:
    [BZOJ1222/Luogu2224][HNOI2001]产品加工
    [BZOJ1079/Luogu2476][SCOI2008]着色方案
    [BZOJ3098]Hash Killer II
    [BZOJ1818][CQOI2010]内部白点
    [BZOJ1497/Luogu4174][NOI2006]最大获利
    [BZOJ2330/Luogu3275][SCOI2011]糖果
    [BZOJ1208/Luogu2286][HNOI2004]宠物收养场
    [BZOJ1054/Luogu4289][HAOI2008]移动玩具
    Com组件介绍
    webBrowse官方说明
  • 原文地址:https://www.cnblogs.com/kenD/p/11135270.html
Copyright © 2011-2022 走看看