Summary of five methods for Python to obtain windows desktop path

  • 2021-07-18 08:36:07
  • OfStack

Here introduced 5 python to get window desktop path method, get this path is of what use? 1 is to output the documents generated by the program to the desktop for easy viewing and editing.

The first two methods are to obtain the absolute path of the current windows desktop through the registry, and the first one is recommended for comparison, because there is no need to install additional extensions, and others can be understood

1. Use the built-in winreg (recommended)


import _winreg
def get_desktop():
  key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
  return _winreg.QueryValueEx(key, "Desktop")[0]

2. win32 extension (third party library required)


import win32api,win32con
def get_desktop():
  key =win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',0,win32con.KEY_READ)
  return win32api.RegQueryValueEx(key,'Desktop')[0]

3. win32 extensions are also required


from win32com.shell import shell, shellcon
def GetDesktopPath():
  ilist =shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP)
  return shell.SHGetPathFromIDList(ilist)

4. path module of os library built into python

This method may fail after the user changes the desktop path.


import os
def GetDesktopPath():
  return os.path.join(os.path.expanduser("~"), 'Desktop')

5. Use the socket module (not recommended)

Of course, this method, Is to get the host name of the current pc, 1 Under normal circumstances, the windows system will set a computer name at the beginning of the first time, this computer name will appear in the user directory under the C disk, for example, my computer name is' jayzhen ', then there will be a directory path: C:\ Users\ jayzhen, at this time my desktop path is: C:\ Users\ jayzhen\ Desktop (the problem is that if you modify the computer name later, this method will not take effect), the code performance is very similar to the fourth


import socket, os
def GetDesktopPath()
 hostname = socket.gethostname()  #socket.getfqdn(socket.gethostname()) 
 basepath = os.path.join("C:\Users\",hostname ) 
 return os.path.join(basepath, 'Desktop')

Related articles: