使用 Python 3 读写 Windows“标签”

use*_*687 4 windows com winapi pywin32 win32com

在 Windows 中,图像文件可以被标记。可以通过右键单击文件,单击“详细信息”选项卡,然后单击“标签”属性值单元格来查看和编辑这些标签。

我希望能够使用 Python 3 读取和写入这些标签。

这不是 EXIF 数据,因此 EXIF 解决方案不起作用。我相信它是 Windows 属性系统的一部分,但我在开发中心找不到参考。我查看了 win32com.propsys,也看不到任何内容。

我以前编写过一个程序,曾经执行过此操作,但后来我丢失了它,所以我知道这是可能的。以前我没有使用 pywin32,但任何解决方案都很棒。我想我用过windll,但我不记得了。

Sim*_*ier 5

以下是一些通过以下方式使用IPropertyStore 接口的propsys示例代码:

import pythoncom
from win32com.propsys import propsys
from win32com.shell import shellcon

# get PROPERTYKEY for "System.Keywords"
pk = propsys.PSGetPropertyKeyFromName("System.Keywords")

# get property store for a given shell item (here a file)
ps = propsys.SHGetPropertyStoreFromParsingName("c:\\path\\myfile.jpg", 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)

# build an array of string type PROPVARIANT
newValue = propsys.PROPVARIANTType(["hello", "world"], pythoncom.VT_VECTOR | pythoncom.VT_BSTR)

# write property
ps.SetValue(pk, newValue)
ps.Commit()
Run Code Online (Sandbox Code Playgroud)

这段代码对于任何 Windows 属性来说都是非常通用的。

我使用System.Keywords是因为它对应于您在属性表中看到的 jpeg 的“tags”属性。

该代码适用于 jpeg 和其他格式的读取( GetValue) 属性,但并非所有 Windows 编解码器都支持属性写入( SetValue),例如,它不适用于将扩展属性写回 .png。

  • 系统.关键字?!这个我就捂脸了!非常感谢您的帮助,这工作完美,您的代码可爱又干净。我不知道该怎么感谢你才足够! (2认同)