How to get Desktop location?

Ben L picture Ben L · Dec 14, 2015 · Viewed 41.6k times · Source

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.

Answer

user559633 picture user559633 · Dec 14, 2015

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)