Home > Mobile >  Python get Desktop Path directly on Windows
Python get Desktop Path directly on Windows

Time:10-10

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?

CodePudding user response:

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)

CodePudding user response:

This worked for me. The idea is to get the user first using os.getlogin():

usr_dir = os.path.join(os.getcwd().split(os.getlogin())[0], os.getlogin())
desktop = os.path.join(usr_dir, "Desktop")
  • Related