python--獲取當前文件絕對路徑的幾種方式對比


背景

  1. 在自動化測試中(ui\interface),常需要用到絕對路徑,以此增強腳本的健壯性
  2. python內置os模塊提供了三種獲取當前目錄絕對路徑的方式,現在來比較一下

獲取當前文件的路徑

  1. os.getcwd()
  2. os.path.abspath(__file__)
  3. 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__)

-- 返回當前文件的標准路徑,而非軟鏈接所在的路徑

總結

  1. 強烈推薦使用 os.path.realpath(\_\_file\_\_)
  2. 利用 os.path.split() 將路徑與文件名分離,再通過項目路徑與其他路徑拼接的方式,獲得其他目錄的絕對路徑
dir_path = os.path.split(os.path.realpath(__file__))[0]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM