Each Answer to this Q is separated by one/two green lines.
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:
txtName is the txt File’s name (with full path).
I get the error:
IOError: [Errno 2] No such file or directory: '%HOMEPATH%/DESKTOP'
I want the script to work on any computer.
On Unix or Linux:
import os desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')
import os desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
and to add in your command:
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"))
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"))
For 3.5+ you can use pathlib:
import pathlib desktop = pathlib.Path.home() / 'Desktop'
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://stackoverflow.com/a/626927/7273599
All those answers are intrinsecally wrong : they only work for english sessions.
You should check the XDG directories instead of supposing it’s always
Here’s the correct answer: How to get users desktop path in python independent of language install (linux)
import os file1 =os.environ["HOMEPATH"] + "\Desktop\myfile.txt"
Just an addendum to @tpearse accepted answer:
In an embedded environment (c++ programm calling a python environment)
was the only one that worked. Seems like
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)