How to get Desktop location?
Asked Answered
I

11

49

I'm using Python on Windows and I want a part of my script to copy a file from a certain directory (I know its path) to the Desktop.

I used this:

shutil.copy(txtName, '%HOMEPATH%/desktop')

While txtName is the txt File's name (with full path).

I get the error:

IOError: [Errno 2] No such file or directory: '%HOMEPATH%/DESKTOP'

Any help?

I want the script to work on any computer.

Ironlike answered 14/12, 2015 at 20:15 Comment(1)
All answers (except GPCracker) are incorrect, because the desktop folder can be moved outside HOMEPATH.Sightread
O
32

You can use os.environ["HOMEPATH"] to get the path. Right now it's literally trying to find %HOMEPATH%/Desktop without substituting the actual path.

Maybe something like:

shutil.copy(txtName, os.path.join(os.environ["HOMEPATH"], "Desktop"))
Oust answered 14/12, 2015 at 20:23 Comment(2)
os.path.expanduser("~/Desktop") works on Linux and WindowsDuwe
@dashesy: You should make that an answer - it's better than any of the others.Kilah
T
65

On Unix or Linux:

import os
desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') 

on Windows:

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

and to add in your command:

shutil.copy(txtName, desktop)
Tews answered 14/12, 2015 at 20:25 Comment(6)
@BenL please vote up or accept if you found it helpful or if it solved your question.Tews
both you and the one above you had great answers. wish I could accept to you both. voted up now. thank you!Ironlike
In both Windows and Linux this seems to work: os.path.expanduser("~/Desktop")Duwe
There is no need for the inner os.path.join() call. Also, the first solution works for Windows too: there is no need for the second solution.Ioannina
@ChauLoi yes it is, I tested it on Mac, it gives you the parent folder of userNondisjunction
This is no longer reliable on Windows 10. The Desktop may be located in OneDrive, either a personal account or business.Nichani
D
38

This works on both Windows and Linux:

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

# the above is valid on Windows (after 7) but if you want it in os normalized form:
desktop = os.path.normpath(os.path.expanduser("~/Desktop"))
Duwe answered 31/7, 2018 at 16:49 Comment(6)
Would this work on non-English Windows machines? When I checked back around 2010 this was not the case.Ioannina
@EricLebigot I do not have non-English Windows machine to test, can you let us know?Duwe
That will produce 'C:\\Users\\user/Desktop' on Windows ... This will work on Win desktop = os.path.expanduser("~\\Desktop")Garnet
@Sabrina that is valid, in newer Widows you can use / and it is preferred because you won't have to escape it. You can use os.path.normpath if you care.Duwe
It does work on non-English (Spanish) machine, and it actually outputs what Sabrina says.Tumpline
It does not work on non-English Linux machine, because my desktop folder is actually /home/andreymal/Рабочий столSightread
O
32

You can use os.environ["HOMEPATH"] to get the path. Right now it's literally trying to find %HOMEPATH%/Desktop without substituting the actual path.

Maybe something like:

shutil.copy(txtName, os.path.join(os.environ["HOMEPATH"], "Desktop"))
Oust answered 14/12, 2015 at 20:23 Comment(2)
os.path.expanduser("~/Desktop") works on Linux and WindowsDuwe
@dashesy: You should make that an answer - it's better than any of the others.Kilah
E
30

For 3.5+ you can use pathlib:

import pathlib

desktop = pathlib.Path.home() / 'Desktop'
Ensoll answered 28/4, 2020 at 7:57 Comment(2)
My desktop isn't located on my C:\, and all other options don't work directly. I like this solution!Peba
This seems to be the modern way to do this.Bushman
S
14

I can not comment yet, but solutions based on joining location to a user path with 'Desktop' have limited appliance because Desktop could and often is being remapped to a non-system drive. To get real location a windows registry should be used... or special functions via ctypes like https://mcmap.net/q/356046/-how-do-i-find-the-windows-common-application-data-folder-using-python

Sfax answered 16/4, 2017 at 9:11 Comment(0)
I
6

All those answers are intrinsecally wrong : they only work for english sessions.

You should check the XDG directories instead of supposing it's always 'Desktop'.

Here's the correct answer: How to get users desktop path in python independent of language install (linux)

Irmgard answered 8/1, 2020 at 12:50 Comment(2)
This answer is intrinsically wrong: It only works for Linux. :)Ensoll
True :) I may have been tired and forgot the bit about windows.Irmgard
E
1

Try this:

import os
file1 =os.environ["HOMEPATH"] + "\Desktop\myfile.txt" 
Evacuation answered 19/10, 2019 at 7:22 Comment(0)
K
1

When Windows Explorer is in This PC, user can change the Desktop folder to any location instead of the default C:\Users\username\Desktop, so it's wrong to simply concat home directory's location and Desktop to get Desktop's location. Instead you should get the location from the registry Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop.

Extracted string may contain unexpanded environment variables, such as %USERPROFILE%\Desktop. To expand them, use os.path.expandvars().

import winreg
import os

with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders") as key:
    # Extracted string may contain unexpanded environment variables, such as "%USERPROFILE%\Desktop"
    desktop_dir, _ = winreg.QueryValueEx(key, "Desktop")
    # To expand the environment variable in the above string, use this form
    desktop_dir = os.path.expandvars(winreg.QueryValueEx(key, "Desktop")[0])
Krouse answered 11/5 at 3:56 Comment(0)
O
0

Just an addendum to @tpearse accepted answer:

In an embedded environment (c++ programm calling a python environment)

os.path.join(os.environ["HOMEPATH"], "Desktop")

was the only one that worked. Seems like

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

does not return a usable path for the embedded environment (at least not in my one; But some environmental settings in visual studio could be missing in my setup)

Opinion answered 6/10, 2021 at 8:47 Comment(0)
I
0

Simple and Elegant Try this to access file in Desktop:

import os
import pathlib
import pandas as pd

desktop = pathlib.Path.home() / 'Desktop' / "Panda's" / 'data'
print(desktop) #check you path correct ?
data = pd.read_csv(os.path.joinn(desktop),'survey_results_public.csv')

Congrants!

Immunotherapy answered 29/7, 2022 at 8:26 Comment(1)
If you clean up your answer (remove pandas / mistyped os.path.joinn that does nothing because of misplaced bracket) you end up with a duplicate answerEnsoll
C
0
def get_desktop_path():
    import platform
    if platform.system() == 'Windows':
        try:
            import winreg
            reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
            desktop = winreg.QueryValueEx(reg_key, 'Desktop')[0]
            winreg.CloseKey(reg_key)
        except:
            desktop = "None"
    else:
        from pathlib import Path
        desktop = Path.home() / 'Desktop'
        if not os.path.exists(desktop):
            desktop = os.path.normpath(os.path.expanduser("~/Desktop"))
    if not os.path.exists(desktop):
        desktop = os.path.normpath(os.path.expanduser("~"))
        print(f"архив будет сохранен сюда: {desktop}")
    else:
        print(f"архив будет сохранен на рабочий стол")
    return desktop
Cassidy answered 24/10, 2023 at 20:28 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Ulent

© 2022 - 2024 — McMap. All rights reserved.