PythonでWindows ファイルの拡張プロパティを読み書きする
PythonでWindowsの拡張プロパティを読んだり書いたりするサンプルコードを紹介します。
C#ならWindowsAPICodepackを使えば簡単、サンプルコードも、ググればすぐに見つかると思います。でも、Pythonではどうすんのかわからん、と、知人からヘルプ要請がきたので、軽く調べてみると確かにググってもパッと出てこない。英語の記事はあるんだけど、日本語記事は意外に見つからない。ということで、記事化しておくことにした。読んでくるだけなら、Shell.Applicationで、GetDetailsOfでも良いけど、書き込みができないね。いずれにしても、pywin32が必要だから、pipでいれてね。
Windowsの拡張プロパティのタグを読み書き編集するサンプル
# # Windows 拡張プロパティのタグを編集するサンプルコード # by たのじぃ # import pythoncom from win32com.propsys import propsys from win32com.shell import shellcon # タグの読み込み file = r"C:\TEST\TEST.JPG" # get PROPERTYKEY for "System.Keywords" pk = propsys.PSGetPropertyKeyFromName("System.Keywords") # get property store for a given shell item (here a file) ps = propsys.SHGetPropertyStoreFromParsingName(file, None, shellcon.GPS_READWRITE, propsys.IID_IPropertyStore) # read & print existing (or not) property value, System.Keywords type is an array of string keywords = ps.GetValue(pk).GetValue() print(keywords) # タグの書き込み keywords = ['Tag1','Tag2','Tag3'] # build an array of string type PROPVARIANT newValue = propsys.PROPVARIANTType(keywords, pythoncom.VT_VECTOR | pythoncom.VT_BSTR) # write property ps.SetValue(pk, newValue) ps.Commit()
Windowsの拡張プロパティのタグを読むだけサンプル
# # Windows 拡張プロパティのタグを読み込むサンプルコード # by たのじぃ # import os from win32com.client import Dispatch shell = Dispatch("Shell.Application") file = r"C:\TEST\TEST.JPG" ns = shell.NameSpace("C:\\TEST") print(ns.Items()) for i in ns.Items(): # Check here with the specific filename if str(i) == "TEST.JPG": tags = ns.GetDetailsOf(i,18).split(';') for s in tags: print(s.strip())
GetDetailsOf内の番号は、18がタグ。いろんな情報を取ってくるのが目的ならこっちのほうが使いやすいかも。番号と中身の対照表は、あちこちにあると思いますが、参考リンク一つだけ貼っときます。例えば、こちら。
ITネタその他もろもろ
GetDetailsOfでファイルプロパティを取得する
クライアントからファイルのプロパティを取得したいという要望があったため、C#でファイルプロパティを取得する際の備忘録です。Shell32を参照してGetDetailsOfでプロパティを取得するまず、Shell32を参照追加します。ソリューシ
dummy
コメント
0 件のコメント :
コメントを投稿