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.

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)

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 'Desktop'.

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

Try this:

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)

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)