天天看點

os.getcwd 和os.path.abspath解讀

os.getcwd && os.path.abspath

1、os.getcwd():

擷取目前工作目錄,也就是在哪個目錄下運作這個程式。

假設F:\aaa\bbb\ccc目錄下有個檔案 TestDir.py,列印目前工作目錄。進入windows指令行視窗

os.getcwd 和os.path.abspath解讀

os.path是專門用來解析位址的,

如何獲得當下程式運作的完整位址可以用os.path.abspath(file)

注意__file__屬于該方法的特殊用法,不能在其他地方單獨使用否則報錯,因為沒定義。

2、os.path.abspath()

隻有當在腳本中執行的時候,os.path.abspath(file)才會起作用,因為該指令是擷取的目前執行腳本的完整路徑,如果在互動模式或者terminate 終端中運作會報沒有__file__這個錯誤:

os.getcwd 和os.path.abspath解讀

不是取絕對路徑麼?怎麼不是真實的完整路徑?上級目錄不見了???

os.getcwd 和os.path.abspath解讀

另外的,舉例有:

os.getcwd 和os.path.abspath解讀