python --获取桌面路径
- 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]
-
- 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]
-
- from win32com.shell import shell, shellcon
- def GetDesktopPath():
- ilist =shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP)
- return shell.SHGetPathFromIDList(ilist)
-
- import os
- def GetDesktopPath():
- return os.path.join(os.path.expanduser("~"), 'Desktop')
-
当然这个方法,是获取当前pc的主机名,一般情况下,windows系统启用第一次开始时会设置一个电脑名,这个电脑名会出现在C盘下的用户目录下,比如我的电脑名是‘jayzhen’,那么会有一个目录路径:C:\Users\jayzhen,这时候我的桌面路径就是:C:\Users\jayzhen\Desktop(问题就是如果你随后修改了电脑名,这个方法就不生效了),代码表现的跟第四种很像
- 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')
-
- import win32com.client
- shell = win32com.client.Dispatch("WScript.Shell")
- print(shell.SpecialFolders("Desktop"))
-