Windows 專用:win32com 實作
# 需安裝:pip install pywin32
from win32com.shell import shell, shellcon
def get_desktop_path() -> str:
"""
透過 Windows Shell API 獲取當前用戶桌面路徑
對應 CSIDL_DESKTOP (0x0000)
"""
# 獲取桌面資料夾的 PIDL (Item ID List)
pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP)
# 轉換為檔案系統路徑
path = shell.SHGetPathFromIDList(pidl)
return path
print(get_desktop_path())
# 輸出範例:C:\Users\Username\Desktop
跨平台替代方案(推薦)
方法一:pathlib + 環境變數(標準庫,無依賴)
from pathlib import Path
import os
def get_desktop_cross_platform() -> Path:
# Windows: %USERPROFILE%\Desktop
# macOS/Linux: ~/Desktop
return Path.home() / 'Desktop'
# 進階:支援 OneDrive 重定向桌面 (Windows)
def get_desktop_smart() -> Path:
home = Path.home()
# 檢查 OneDrive 桌面
onedrive = os.environ.get('OneDrive')
if onedrive and (Path(onedrive) / 'Desktop').exists():
return Path(onedrive) / 'Desktop'
return home / 'Desktop'
print(get_desktop_smart())
方法二:platformdirs 庫(專業跨平台路徑處理)
# pip install platformdirs
from platformdirs import user_desktop_path
path = user_desktop_path()
print(path)
# Windows: C:\Users\name\Desktop
# macOS: /Users/name/Desktop
# Linux: /home/name/Desktop (遵循 XDG 標準)
常見應用場景
from pathlib import Path
desktop = get_desktop_smart()
# 1. 儲存匯出檔案
export_file = desktop / f'export_{datetime.now():%Y%m%d_%H%M%S}.csv'
export_file.write_text('col1,col2\nval1,val2', encoding='utf-8-sig')
# 2. 讀取用戶放在桌面的設定檔
config_file = desktop / 'myapp_config.json'
if config_file.exists():
import json
config = json.loads(config_file.read_text())
# 3. 建立捷徑
shortcut = desktop / 'MyApp.lnk'
# 需額外用 winshell 或 pywin32 建立 .lnk
?>
注意事項
win32com 僅限 Windows,且需安裝 pywin32(含 C 擴充,虛擬環境需確保編譯環境)
- 企業環境桌面可能被組策略重定向至網路磁碟,
SHGetSpecialFolderLocation 會正確解析
- 跨平台專案強烈建議用
pathlib + platformdirs
- Linux 桌面路徑遵循 XDG Base Directory Specification,可能非
~/Desktop