When Windows Explorer is in This PC
, user can change the Desktop folder to any location instead of the default C:\Users\username\Desktop
, so it's wrong to simply concat home directory's location and Desktop
to get Desktop's location. Instead you should get the location from the registry Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop
.
Extracted string may contain unexpanded environment variables, such as %USERPROFILE%\Desktop
. To expand them, use os.path.expandvars()
.
import winreg
import os
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders") as key:
# Extracted string may contain unexpanded environment variables, such as "%USERPROFILE%\Desktop"
desktop_dir, _ = winreg.QueryValueEx(key, "Desktop")
# To expand the environment variable in the above string, use this form
desktop_dir = os.path.expandvars(winreg.QueryValueEx(key, "Desktop")[0])