zoukankan      html  css  js  c++  java
  • python中os.path.dirname(__file__)和sys.path[0]使用

    python中os.path.dirname(__file__)的使用


     (1).当"print os.path.dirname(__file__)"所在脚本是以完整路径被运行的, 那么将输出该脚本所在的完整路径,比如:
          python c:/python27/test/test.py
          那么将输出 c:/python27/test/
     (2).当"print os.path.dirname(__file__)"所在脚本是以相对路径被运行的, 那么将输出空目录,比如:
         python test.py

         那么将输出空字符串

    以下代码可以保证在任何时候都切换到当前执行脚本所在目录中,该当当做公式熟记在心。

    [python] view plain copy
     
      1. abspath = os.path.dirname(__file__)  
      2. sys.path.append(abspath)  
      3. print abspath  
      4. if abspath=='':  
      5.     os.chdir(sys.path[0])      
      6. else:  
      7.     os.chdir(abspath)    
  • 相关阅读:
    SDN第三次作业
    SDN第二次上机作业
    SDN第二次作业
    JAVA小记
    算法笔记
    排序
    SDN期末作业
    SDN第五次上机作业
    SDN第四次上机作业
    SDN第四次作业
  • 原文地址:https://www.cnblogs.com/YingxuanZHANG/p/8805805.html
Copyright © 2011-2022 走看看