2

Ive seen answers that finds the user's path, and then concatenating it with desktop, Such as:

desktop = os.path.expanduser("~/Desktop")

and

desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') 

However it doesn't work when the device has non-default extensions:

C:\\Users\\NAME\\OneDrive\\Desktop

or non-english extension:

C:\\Users\\NAME\\OneDrive\\桌面

I ended up doing this as an emergency response:

possible_desktop_ext = ['Desktop', 'OneDrive\\Desktop', 'OneDrive\\桌面']

I can definitely see the list expanding exponentially in the future, and I don't really like the feeling of doing this every time I find a new extension.

So what is the most reliable way of retrieving the desktop's path?

Electron X
  • 330
  • 1
  • 10
  • Maybe this could be useful for your question: [https://stackoverflow.com/questions/34275782/how-to-get-desktop-location](https://stackoverflow.com/questions/34275782/how-to-get-desktop-location) – Berk Hakbilen Oct 09 '22 at 17:12

1 Answers1

1

This is adapted from https://stackoverflow.com/a/626927/5987, I urge you to go to it and give it the recognition it deserves.

import ctypes
from ctypes import wintypes, windll

CSIDL_DESKTOP = 0

_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
                            ctypes.c_int,
                            wintypes.HANDLE,
                            wintypes.DWORD, wintypes.LPCWSTR]

path_buf = ctypes.create_unicode_buffer(wintypes.MAX_PATH)
result = _SHGetFolderPath(0, CSIDL_DESKTOP, 0, 0, path_buf)
print(path_buf.value)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622