I am new to the os library and I was wondering how I could find the path for any user who uses windows and access their desktop directory using python. Thanks in advance!
Asked
Active
Viewed 4,725 times
0
-
Windows desktop paths are typically of the form `C:\Users\{username}\Desktop`. – Jonah Bishop Nov 27 '18 at 02:18
3 Answers
5
You can do it by using os.environ mapping and add the Desktop
path
import os
print(os.environ['USERPROFILE'] + '\Desktop')

Andreas
- 2,455
- 10
- 21
- 24
-
This should not be marked an a correct answer. It will only work if the user is on an English system and if they have not moved their Desktop folder, like OneDrive does for instance. The answers usingCSIDL_DESKTOP below is the correct one. – Renaud Bompuis Jan 01 '23 at 06:07
5
Previous solutions won't work if the Desktop folder was manually changed by the user (to a OneDrive folder or whatever...).
This will work:
from win32com.shell import shell, shellcon
desktop = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)

Simdan
- 391
- 1
- 4
- 11
2
You can also try to query the registry.
import subprocess
import sys
import os
if sys.platform == "win32":
command = r'reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop"'
result = subprocess.run(command, stdout=subprocess.PIPE, text = True)
desktop = result.stdout.splitlines()[2].split()[2]
else:
desktop = os.path.expanduser("~/Desktop")
print(desktop)
#D:\Desktop

unwave
- 133
- 6