Last active
November 17, 2021 07:05
-
-
Save elibroftw/cdf6bd2c3b072cf87375256d6511348c to your computer and use it in GitHub Desktop.
A better way to resolve special or known folder names to their usable paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| No Copyright. Public Domain. | |
| Version: 1.0.4 | |
| Known Issues: Common home folders like Documents, Music, Videos, arem missing. | |
| """ | |
| from functools import lru_cache | |
| from contextlib import suppress | |
| import sys | |
| from uuid import UUID | |
| from pathlib import Path | |
| try: | |
| import pythoncom | |
| except ImportError: | |
| import subprocess | |
| subprocess.run([sys.executable, '-m', 'pip', 'install', 'pywin32', '--user']) | |
| import pythoncom | |
| import pywintypes | |
| from win32com.shell import shell | |
| @lru_cache(maxsize=1) | |
| def _get_name_to_paths(): | |
| """ | |
| Internal function to get the known folder name to path mapping. | |
| Returns a dict of Spceial name -> path for all the FolderIds known to KnownFolderManager | |
| """ | |
| mgr = pythoncom.CoCreateInstance(shell.CLSID_KnownFolderManager, None, | |
| pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IKnownFolderManager) | |
| ids = mgr.GetFolderIds() | |
| names_to_path = {} | |
| for id in ids: | |
| know_folder = mgr.GetFolder(id) | |
| defn = know_folder.GetFolderDefinition() | |
| with suppress(pywintypes.com_error): | |
| names_to_path[defn['Name'].capitalize()] = Path(know_folder.GetPath()) | |
| return names_to_path | |
| def resolve_known_folder(name): | |
| return _get_name_to_paths()[name.capitalize()] | |
| if __name__ == '__main__': | |
| assert resolve_known_folder('Desktop') == Path.home() / 'Desktop' | |
| assert resolve_known_folder('Downloads') == Path.home() / 'Downloads' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment