python获取当前工作目录

在编程中经常需要用到当前脚本的工作目录,以下是python脚本获取当前工作目录的语句。例test.py

  1. import inspect  
  2. dir = inspect.getfile(inspect.currentframe())  
  3. print dir 

打印出的是当前语句所在的或者说是包含当前语句的函数所在的脚本的目录。

放在/home/zhang/下执行:

./test.py       输出./test.py

python test.py      输出test.py

/home/zhang/test.py     输出/home/zhang/test.py

我们要获得的是路径,下面的程序会实现:

  1. import os,inspect  
  2. dir = inspect.getfile(inspect.currentframe())  
  3. if os.path.isdir(dir):  
  4.     print dir  
  5. elif os.path.isfile(dir):  
  6.     print os.path.dirname(dir) 

执行/home/zhang/test.py      输出/home/zhang

也可以用print   __file__输出效果是一样的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章