Path to User Desktop Using Python

Path to User Desktop Using Python

This may seem stupid to a few, but I was wondering if there was some code to find out the operating system of the present user, and then the path to his Desktop using python.

1

2 Answers

On a default Ubuntu running Python 2.7 you can use the following commands

#!/usr/bin/env python

import os
import platform

userhome = os.path.expanduser('~')
desktop = userhome + '/Desktop/'
useros = platform.system() # returns e.g. 'Linux' 'Windows' 
distribution = platform.linux_distribution() 'in case it's a Unix

When coding a cross platfrom application you should be aware that not all desktop environments make use of a desktop directory. This will even be true for some XDG desktops.

  • Our code should therefore not rely on the presence of a desktop directory.

In case you code for different locales you need to parse the name given for the desktop directory from the users's xdg desktop configuration (see How can I get the (XDG) Default User Directories from Python?).

8
import subprocess
import os.path

try:
    return subprocess.check_output(['xdg-user-dir', 'DESKTOP'])
except:
    return os.path.expanduser("~/Desktop")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.