Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

How do I find the Windows common application data folder using Python?

I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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 SettingsAll 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 SettingsAll UsersApplication Data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...