我希望我的应用程序存储一些数据供所有用户访问.使用Python,我如何找到数据的去向?
如果您不想为winpaths等第三方模块添加依赖项,我建议使用Windows中已有的环境变量:
Windows中可用的环境变量是什么?
具体而言,您可能希望ALLUSERSPROFILE
获取公共用户配置文件文件夹的位置,该文件夹位于Application Data目录所在的位置.
例如:
C:\> python -c "import os; print os.environ['ALLUSERSPROFILE']" C:\Documents and Settings\All Users
编辑:看看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
来自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("~")
要获取所有用户的app-data目录,而不是当前用户,只需使用shellcon.CSIDL_COMMON_APPDATA
而不是shellcon.CSIDL_APPDATA
.
看看http://ginstrom.com/code/winpaths.html.这是一个简单的模块,可以检索Windows文件夹信息.该模块实现get_common_appdata
为所有用户获取App Data文件夹.