背景
- 在自動化測試中(ui\interface),常需要用到絕對路徑,以此增強腳本的健壯性
- python內置os模塊提供了三種獲取當前目錄絕對路徑的方式,現在來比較一下
獲取當前文件的路徑
- os.getcwd()
- os.path.abspath(__file__)
- os.path.realpath(__file__)
os.getcwd()
- 返回「當前工作路徑」
- 工作路徑是腳本運行/調用/執行的地方,而「不是腳本本身的地方」
- 「當前文件路徑」跟「當前工作路徑」沒關系
- 即獲取文件絕對路徑時,此方式不可用
- 源碼如下:
def getcwd(*args, **kwargs): # real signature unknown
""" Return a unicode string representing the current working directory. """
pass
os.path.abspath(__file__)
- 返回當前文件的絕對路徑
- 存在軟連接時,返回軟連接文件路徑
- 源碼如下:
def abspath(path):
"""Return the absolute version of a path."""
try:
return normpath(_getfullpathname(path))
except (OSError, ValueError):
return _abspath_fallback(path)
os.path.realpath(__file__)
-- 返回當前文件的標准路徑,而非軟鏈接所在的路徑
總結
- 強烈推薦使用
os.path.realpath(\_\_file\_\_)
- 利用 os.path.split() 將路徑與文件名分離,再通過項目路徑與其他路徑拼接的方式,獲得其他目錄的絕對路徑
dir_path = os.path.split(os.path.realpath(__file__))[0]