• os.path.dirname(__file__)方法详解


    该测试脚本所在的位置:D:第1层第2层第3层第4层第5层 est11.py

    1.  import os  
    2.  #该文件所在位置:D:第1层第2层第3层第4层第5层	est11.py  
    
    4.  path1 = os.path.dirname(__file__)  
    5.  print(path1)#获取当前运行脚本的绝对路径  
    
    7.  path2 = os.path.dirname(os.path.dirname(__file__)) #  
    8.  print(path2)#获取当前运行脚本的绝对路径(去掉最后一个路径)  
    
    10.  path3 = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))  
    11.  print(path3)#获取当前运行脚本的绝对路径(去掉最后2个路径)  
    
    13.  path4 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))  
    14.  print(path4)#获取当前运行脚本的绝对路径(去掉最后3个路径)  
    
    16.  path5 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))  
    17.  print(path5)#获取当前运行脚本的绝对路径(去掉最后4个路径)  
    
    19.  path6 = os.__file__                  #获取os所在的目录  
    20.  print(path6)  

    结果:

    1.  C:Python352python.exe D:/第1层/第2层/第3层/第4层/第5层/test11.py  
    2.  D:/第1层/第2层/第3层/第4层/第5层  
    3.  D:/第1层/第2层/第3层/第4层  
    4.  D:/第1层/第2层/第3层  
    5.  D:/第1层/第2层  
    6.  D:/第1层  
    7.  C:Python352libos.py  
    8.
    9.  Process finished with exit code 0

    os.path.dirname(file)返回脚本的路径,但是需要注意一下几点:

    • 必须是实际存在的.py文件,如果在命令行执行,则会引发异常NameError: name 'file' is not defined;
    • 在运行的时候如果输入完整的执行的路径,则返回.py文件的全路径如:Python c:/test/test.py 则返回路径 c:/test,如果是python test.py 则返回空;
    • 结合os.path.abspath用,效果会好,如果大家看过一些python架构的代码的话,会发现经常有这样的组合:os.path.dirname(os.path.abspath(file)),os.path.abspath(file)返回的是.py文件的绝对路径。

    这就是os.path.dirname(file)的用法,其主要总结起来有:

    • 不要在命令行的形式来进行os.path.dirname(file)这种形式来使用这个函数;
    • 结合os.path.abspath()使用
    1.  import os  
    2.  #该文件所在位置:D:第1层第2层第3层第4层第5层	est11.py  
    
    4.  path1 = os.path.dirname(__file__)  
    5.  print(path1)#获取当前运行脚本的绝对路径  
    
    7.  path2 = os.path.dirname(os.path.dirname(__file__)) #  
    8.  print(path2)#获取当前运行脚本的绝对路径(去掉最后一个路径)  
    
    10.  path3 = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))  
    11.  print(path3)#获取当前运行脚本的绝对路径(去掉最后2个路径)  
    
    13.  path4 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))  
    14.  print(path4)#获取当前运行脚本的绝对路径(去掉最后3个路径)  
    
    16.  path5 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))  
    17.  print(path5)#获取当前运行脚本的绝对路径(去掉最后4个路径)  
    
    19.  path6 = os.__file__                  #获取os所在的目录  
    20.  print(path6)  
    
  • 相关阅读:
    敏捷思维-架构设计中的方法学(12)Refactoring
    敏捷思维-架构设计中的方法学(11)精化和合并
    敏捷思维-架构设计中的方法学(8)架构愿景
    敏捷思维-架构设计中的方法学(10)分层 (下)
    Agile 敏捷建模思想 作者:林星
    敏捷思维-架构设计中的方法学(9)分层 (上)
    敏捷思维-架构设计中的方法学(13)稳定化
    敏捷思维-架构设计中的方法学(15)进一步阅读
    hdu 1829+hdu 1856(并查集)
    hdu 1050+hdu 1789+hdu 3177(贪心)
  • 原文地址:https://www.cnblogs.com/yibeimingyue/p/13744146.html
Copyright © 2020-2023  润新知