python慎用os.getcwd() ,除非你知道【文件路徑與當前工作路徑的區別】
當你搜索 “獲取當前文件路徑” 時,有的文章會提到用os.getcwd(),但是這玩意要慎用!
廢話不多說,直接上例子:
E:\program_software\Pycharm\ytb\ytb_api\api\views.py 文件內容如下:
path1 = os.path.abspath(os.path.dirname(os.getcwd())) print('path1: ', path1)
在別處調用後:
結果並不是想要的當前文件路徑。
為什麼會這樣?
去看getcwd源碼:
解釋:return 得到當前工作路徑(working directory)
那這個working directory到底是什麼?
繼續搜索:
翻譯一下:
當前工作路徑 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()))
手敲不易,如果有幫助,請您給我點個推薦,感謝。