How to retrieve the Desktop path in Windows with Python

In order to retrieve the desktop directory with Python, you can built it based on the concatenation of the USERPROFILE environment variable of Windows with the OS module of Python. As you may know, the OS module provides a portable way of using operating system dependent functionality. Of our interest, the submodule of our interest is the os.path that allow you to manipulate paths on the system and the os.environ, known as a mapping object that returns a dictionary of the user's environmental variables.

To get started, we'll explain step by step what every piece of code means. The initial step is to obtain the current users directory, this can be obtained through the USERPROFILE environment variable of Windows, with python, use os.environ function to retrieve it:

import os

# Prints the current user's directory: C:\Users\sdkca
print(os.environ['USERPROFILE'])
# Or print(os.environ.get("USERPROFILE"))

Knowing this, you can automatically assume the Desktop directory of the user appending the Desktop keyword at the end of the path obtained from the mentioned environment variable. This can be made in a single line of code:

import os

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

# Prints: C:\Users\sdkca\Desktop
print("The Desktop path is: " + desktop)

Happy coding !

This could interest you

Become a more social person