zoukankan      html  css  js  c++  java
  • python慎用os.getcwd() ,除非你知道【文件路径与当前工作路径的区别】

    当你搜索 "获取当前文件路径" 时,有的文章会提到用os.getcwd(),但是这玩意要慎用!

    废话不多说,直接上例子:

    E:program_softwarePycharmytbytb_apiapiviews.py 文件内容如下:

    path1 = os.path.abspath(os.path.dirname(os.getcwd()))
    print('path1: ', path1)

    在别处调用后:

    结果并不是想要的当前文件路径。

    为什么会这样?

    去看getcwd源码:

    解释:return 得到当前工作路径(working directory)

    那这个working directory到底是什么?

    继续搜索:

     

     翻译一下:

    当前工作路径 working directory 就是脚本运行/调用/执行的地方,而不是脚本本身的地方。

    也就是说「当前文件路径」「当前工作路径」没关系,

    即os.getcwd() 返回值跟你的 Python 文件路径没关系,

    如果要获得「文件路径」你得使用 __file__

    比如,我想要的是当前文件的绝对路径,那就需要这俩哥出场了:

    还以E:program_softwarePycharmytbytb_apiapiviews.py 举例子:

    # Return the absolute version of a path. 获取当前文件的绝对路径
    print(os.path.abspath(__file__)) 
    # E:/program_software/Pycharm/ytb/ytb_api/api/views.py
    
    
    # Returns the directory component of a pathname 获取当前文件所属的文件夹
    print(os.path.dirname(__file__))  
    # E:/program_software/Pycharm/ytb/ytb_api/api
    

      

    搭配使用,返回当前文件所在文件夹的绝对路径(这两个结果是一样的):

    path1 = os.path.dirname(os.path.abspath(__file__))
    print(path1)
    # E:/program_software/Pycharm/ytb/ytb_api/api
    
    path2 = os.path.abspath(os.path.dirname(__file__))
    print(path2)
    # E:/program_software/Pycharm/ytb/ytb_api/api
    

    如果看过些源码的话,会发现很多源码都这么用:

     总结一下:

    「当前文件路径」用  os.path.abspath(os.path.dirname(__file__))

    「当前工作路径」用 os.path.abspath(os.path.dirname(os.getcwd()))

    谢谢各位看官。

      

  • 相关阅读:
    作业5:扒开系统调用的三层皮(下) 20135115臧文君
    课本学习笔记2:第五章 20135115臧文君
    Linux及安全实践二
    Linux内核分析 期中总结
    Linux内核分析08
    Linux内核分析07
    Linux内核分析06
    Linux内核分析 05
    Linux内核分析04
    Linux内核分析 03
  • 原文地址:https://www.cnblogs.com/liangmingshen/p/12794631.html
Copyright © 2011-2022 走看看