python で Windows の My Pictures フォルダのパスを取得(OneDrive対応)

python でピクチャフォルダのパスを取得したくて調べました。

OneDrive を使用しているとリダイレクトされてるので、環境変数から組み立てるのではだめでした。

ついでに Local AppData のパスも取得してます。

import ctypes.wintypes

CSIDL_LOCAL_APPDATA = 0x1c # SDK の ShlObj_core.h で定義されてる
CSIDL_MYPICTURES = 0x27

buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)

ctypes.windll.shell32.SHGetFolderPathW(0, CSIDL_LOCAL_APPDATA, 0, 0, buf)
print('LOCAL_APPDATA={}'.format(buf.value))

ctypes.windll.shell32.SHGetFolderPathW(0, CSIDL_MYPICTURES, 0, 0, buf)
print('MYPICTURES={}'.format(buf.value))

出力

LOCAL_APPDATA=C:\Users\perce-neige\AppData\Local
MYPICTURES=C:\Users\perce-neige\OneDrive\画像