Python 獲取專案根路徑的程式碼
阿新 • • 發佈:2020-01-09
在 執行,除錯,打包成exe 三個不同場景下獲取跟路徑,用於解決獲取資原始檔絕對路徑問題。
工具類程式碼如下:
import sys import os class pathutil(object): """路徑處理工具類""" def __init__(self): # 判斷除錯模式 debug_vars = dict((a,b) for a,b in os.environ.items() if a.find('IPYTHONENABLE') >= 0) # 根據不同場景獲取根目錄 if len(debug_vars) > 0: """當前為debug執行時""" self.rootPath = sys.path[2] elif getattr(sys,'frozen',False): """當前為exe執行時""" self.rootPath = os.getcwd() else: """正常執行""" self.rootPath = sys.path[1] # 替換斜槓 self.rootPath = self.rootPath.replace("\\","/") def getPathFromResources(self,fileName): """按照檔名拼接資原始檔路徑""" filePath = "%s/resources/%s" % (self.rootPath,fileName) return filePath PathUtil = pathutil() if __name__ == '__main__': """測試""" # path = PathUtil.getPathFromResources("context.ini") print(PathUtil.rootPath)
知識點擴充套件:Python獲取當前目錄和上級目錄
獲取當前檔案的路徑:
import os print '***獲取當前目錄***' print os.getcwd() print os.path.abspath(os.path.dirname(__file__)) # __file__ 為當前檔案,若果在ide中執行此行會報錯,可改為 #d = path.dirname('.') # 但是改為.後,就是獲得當前目錄,接著使用dirname函式訪問上級目錄 print '***獲取上級目錄***' print os.path.abspath(os.path.dirname(os.path.dirname(__file__))) print os.path.abspath(os.path.dirname(os.getcwd())) print os.path.abspath(os.path.join(os.getcwd(),"..")) print '***獲取上上級目錄***' print os.path.abspath(os.path.join(os.getcwd(),"../.."))
總結
以上所述是小編給大家介紹的Python 獲取專案根路徑的程式碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!