I want to call Windows API from Python to get %APPDATA% path

Asked 1 years ago, Updated 1 years ago, 424 views

If you try to get the %APPDATA% Windows path from Python, you can run it with the following command:

importos
os.getenv('APPDATA')

However, I have encountered a rare situation where I think I might not be able to get the correct path, so I would like to try using Windows API to get the path.

Using the Recommended API calls for retrievering your AppData folder paths: found in the Advanced Installer document, I tried the following command, but could not retrieve it:

from ctypes import*

user32 = windowll.user32
AppDataPath=user32.Environment.GetFolderPath(user32.Environment.SpecialFolder.ApplicationData);
print(AppDataPath)

The error is as follows:

AttributeError: function 'Environment' not found

How can I call Windows API from Python and get the %APPDATA% path?

python windows

2023-03-08 14:56

1 Answers

Windows API can be retrieved using SHGetFolderPath.
In this case, use win32com.shell instead of windll.user32.

 from win32 com.shell import shell, shellcon

path=shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0)
print(path)#C:\Users\Hoge\AppData\Roaming


2023-03-08 17:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.