python慎用os.getcwd() ,除非你知道【文件路徑與當前工做路徑的區別】

當你搜索 "獲取當前文件路徑" 時,有的文章會提到用os.getcwd(),可是這玩意要慎用!python

廢話很少說,直接上例子:api

E:\program_software\Pycharm\ytb\ytb_api\api\views.py 文件內容以下:spa

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

在別處調用後:翻譯

結果並非想要的當前文件路徑。3d

 

爲何會這樣?component

去看getcwd源碼:blog

解釋:return 獲得當前工做路徑(working directory)get

 

那這個working directory究竟是什麼?源碼

繼續搜索:io

 

 翻譯一下:

當前工做路徑 working directory 就是腳本運行/調用/執行的地方,而不是腳本自己的地方。

 

也就是說「當前文件路徑」「當前工做路徑」不要緊,

即os.getcwd() 返回值跟你的 Python 文件路徑不要緊,

若是要得到「文件路徑」你得使用 __file__

 

好比,我想要的是當前文件的絕對路徑,那就須要這倆哥出場了:

還以E:\program_software\Pycharm\ytb\ytb_api\api\views.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()))

 

手敲不易,若是有幫助,請您給我點個推薦,感謝。

相關文章
相關標籤/搜索