os.path.dirname(__file__)返回腳本的路徑,但是需要注意一下幾點:
1、必須是實際存在的.py文件,如果在命令行執行,則會引發異常NameError: name '__file__' is not defined
2、在運行的時候如果輸入完整的執行的路徑,則返回.py文件的全路徑如:
Python c:/test/test.py 則返回路徑 c:/test ,如果是python test.py 則返回空
3、結合os.path.abspath用,效果會好,如果大家看過一些python架構的代碼的話,會發現經常有這樣的組合
os.path.dirname(os.path.abspath(__file__)),os.path.abspath(__file__)返回的是.py文件的絕對路徑
這就是os.path.dirname(__file__)的用法,其主要總結起來有:
1、不要已命令行的形式來進行os.path.dirname(__file__)這種形式來使用這個函數
2、結合os.path.abspath()使用python中的os.path.dirname(__file__)的使用