腳本需讀取同目錄下的設定檔、模板、資源檔案。硬編碼絕對路徑不利遷移,需動態獲取腳本所在目錄。
import os
import sys
# 獲取腳本所在目錄(__file__ 為當前檔案路徑)
script_dir = os.path.dirname(os.path.abspath(__file__))
# 組合目標檔案路徑
index_path = os.path.join(script_dir, 'index.html')
print(index_path)
__file__:當前模組檔案路徑(可能為相對路徑)。os.path.abspath():轉為絕對路徑。os.path.dirname():取得目錄部分。os.path.join():跨平台安全拼接路徑。
def get_resource_path(relative_path):
"""相容開發環境與打包後環境"""
if hasattr(sys, '_MEIPASS'):
# PyInstaller 臨時解壓目錄
base_path = sys._MEIPASS
else:
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
__file__ 仍指向模組檔案本身,上述寫法通用。
os.getcwd():返回當前工作目錄,而非腳本目錄。sys.argv[0]:可能為相對路徑、符號連結或不包含路徑(交互模式)。pathlib (Python 3.4+):Path(__file__).parent / 'index.html' 更物件導向。