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__輸出效果是一樣的

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