How do I find the Windows common application data folder using Python?
Solution 1:
If you don't want to add a dependency for a third-party module like winpaths, I would recommend using the environment variables already available in Windows:
- What environment variables are available in Windows?
Specifically you probably want ALLUSERSPROFILE
to get the location of the common user profile folder, which is where the Application Data directory resides.
e.g.:
C:\> python -c "import os; print os.environ['ALLUSERSPROFILE']"
C:\Documents and Settings\All Users
EDIT: Looking at the winpaths module, it's using ctypes so if you wanted to just use the relevant part of the code without installing winpath, you can use this (obviously some error checking omitted for brevity).
import ctypes
from ctypes import wintypes, windll
CSIDL_COMMON_APPDATA = 35
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
ctypes.c_int,
wintypes.HANDLE,
wintypes.DWORD, wintypes.LPCWSTR]
path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH)
result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf)
print path_buf.value
Example run:
C:\> python get_common_appdata.py
C:\Documents and Settings\All Users\Application Data
Solution 2:
From http://snipplr.com/view.php?codeview&id=7354
homedir = os.path.expanduser('~')
# ...works on at least windows and linux.
# In windows it points to the user's folder
# (the one directly under Documents and Settings, not My Documents)
# In windows, you can choose to care about local versus roaming profiles.
# You can fetch the current user's through PyWin32.
#
# For example, to ask for the roaming 'Application Data' directory:
# (CSIDL_APPDATA asks for the roaming, CSIDL_LOCAL_APPDATA for the local one)
# (See microsoft references for further CSIDL constants)
try:
from win32com.shell import shellcon, shell
homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
except ImportError: # quick semi-nasty fallback for non-windows/win32com case
homedir = os.path.expanduser("~")
To get the app-data directory for all users, rather than the current user, just use shellcon.CSIDL_COMMON_APPDATA
instead of shellcon.CSIDL_APPDATA
.