如果您不想添加像 winpaths 这样的第三方模块的依赖项,我建议使用 Windows 中已有的环境变量:
- Windows 中有哪些可用的环境变量? http://windowsitpro.com/article/articleid/23873/what-environment-variables-are-available-in-windows.html
具体来说你可能想要ALLUSERSPROFILE
获取公共用户配置文件文件夹的位置,这是应用程序数据目录所在的位置。
e.g.:
C:\> python -c "import os; print os.environ['ALLUSERSPROFILE']"
C:\Documents and Settings\All Users
EDIT:查看 winpaths 模块,它使用 ctypes,因此如果您只想使用代码的相关部分而不安装 winpath,您可以使用它(显然为了简洁省略了一些错误检查)。
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
运行示例:
C:\> python get_common_appdata.py
C:\Documents and Settings\All Users\Application Data