Open In App

How to Get Windows' Special Folders for Currently Logged-In User Using Python

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Accessing Windows' special folders is a common task faced by most of the developers. A special folder is referred to some predefined directories which is used to store specific types of user data or applications settings. These folders are part of the Windows operating system and provide us with a more efficient way to handle user data. Some examples of special folders are Desktop, Documents, Downloads, AppData, Pictures, etc. In Python, we can easily achieve this task with some built-in Python libraries. A Special folder manages the files and provides us a structured way making it easier for the user and applications to access them.

In this article, we are going to cover all the basic steps to access the special folder path. We will cover all the basic steps with clear and concise examples along with explanations.

Accessing Windows Special Folders

Accessing Windows special folders is a crucial and most common task that a developer will face especially when dealing with applications that interact with user data. Accessing Windows special folders in Python can be done in many ways. We will discuss three ways to achieve this task.

1. Using os module

In this method, we will use os module to get the path of the special folder. In the below example, I have used AppData folder to get its path through our Python code. We will use getenv() method to get the path of our special folders. We can have a look on the below code implementation for more clear understanding.

Python
#importing our os module
import os

#creating our user defined function which will fetch the path of special folder 
def SpecialFolder(folder_id):
    path = os.getenv(folder_id)
    return path 

#driver code 
if __name__ == "__main__":
  	#defining the folder name
    folder_id = 'APPDATA'
    #passing the value to our created function
    path = SpecialFolder(folder_id)
    print("Path : ",path)

Output:

specialfolder
Using os module

2. Using ctypes library

In this method, we will directly interact with the Windows API. We will use the ctypes library of Python to achieve our task. In this example, we have used the same special folder i.e. AppData as used in the previous example. Lets see the below code implementation for more clear understanding.

Python
#importing the necessary module in our code
import ctypes
from ctypes import wintypes

#creating our used defined module which will return the path of special folder
def SpecialFolder(id):
    buf = ctypes.create_unicode_buffer(wintypes.MAX_PATH)
    ctypes.windll.shell32.SHGetFolderPathW(None, id, None, 0, buf)
    return buf.value

#main function
if __name__ == "__main__":

    folder_name = input("Enter Name:")     
    #defining the folder id's of some few special folder
    if folder_name == 'desktop':
        CSIDL = 0
    elif folder_name == 'documents':
        CSIDL = 5
    elif folder_name == 'appdata':
        CSIDL = 26
    elif folder_name == 'local_appdata':
        CSIDL = 28
    path = SpecialFolder(CSIDL)
    #displaying the special folder's path
    print(folder_name,": ",path)

Output:

specialfolder2
Using ctypes library

3. Using winreg module

In this method, we are going to use Windows registry to get the path of our requested special folder. In Python, we can simply achieve this task with the help of winreg module. We will use the same special folder i.e. AppData as we have previously used in our previous two methods.

We will be using two main functions :

winreg.CreateKey(key, sub_key)  

here,

  • key : It is the already open key
  • sub_key : It names the key this method opens or creates.
winreg.OpenKey(key, sub_key, reserved=0, access=KEY_READ)

here,

  • key : It is the already open key
  • sub_key : is a string that identifies the sub_key to open.
  • reserved : It is a reserved integer, and must be zero.
  • access : It is a integer that specifies the access mark.

Lets see the code implementation for getting a clear understanding of the process of getting the path for special folder of windows.

Python
import winreg

# User-defined function to return the path of the special folder
def SpecialFolder(key, sub_key, name):
    # Open the registry key
    try:
        rkey = winreg.OpenKey(key, sub_key)
    except FileNotFoundError:
        print("Registry key not found.")
        return None
    
    # Query the value of the specified name
    try:
        value, regtype = winreg.QueryValueEx(rkey, name)
    except FileNotFoundError:
        print(f"The registry key '{name}' was not found.")
        winreg.CloseKey(rkey)
        return None

    # Close the registry key
    winreg.CloseKey(rkey)

    # Expanding environment variables if present
    expanded_value = winreg.ExpandEnvironmentStrings(value)

    # Return the expanded path
    return expanded_value

# Main function
if __name__ == "__main__":
    # Use the correct subkey and check if 'AppData' exists
    path = SpecialFolder(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\
    CurrentVersion\Explorer\User Shell Folders', 'AppData')
    
    if path:
        print("AppData Path:", path)

Output:

specialfolder3
Using winreg module

Conclusion

Accessing windows special folders is a crucial and common task faced by every developer and specially when developing some applications which interacts with the user data. A special folders are predefined directories which stores some specific type of data. These special folders includes Downloads, AppData, Pictures, local AppData etc. In this article we are covered how to get windows special folders using python. We have covered three methods which includes os module, winreg library and ctypes library. We have covered all the basic concepts with clear and concise examples along with the explanations.


Next Article
Practice Tags :

Similar Reads