【问题标题】:Reading and writing Windows "tags" with Python 3使用 Python 3 读取和写入 Windows“标签”
【发布时间】:2020-08-26 01:18:42
【问题描述】:

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

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

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

我以前写过一个程序,它曾经做过一次,但后来我把它弄丢了,所以我知道这是可能的。以前我在没有 pywin32 的情况下这样做,但任何解决方案都会很棒。我想我用过windll,但我不记得了。

【问题讨论】:

    标签: windows winapi com pywin32 win32com


    【解决方案1】:

    这是一些使用IPropertyStore interface 到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()
    

    此代码对于任何 Windows 属性都非常通用。

    我正在使用System.Keywords,因为这与您在属性表中看到的 jpeg 的“标签”属性相对应。

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

    【讨论】:

    • System.Keywords?!我在这方面打脸!非常感谢您的帮助,这完美无缺,您的代码既可爱又干净。我感激不尽!
    • @Bayes - 用您的复制代码提出另一个问题。
    • @SimonMourier,谢谢。在制作我的复制代码期间,我解决了这个问题。 :) 最后一件事,按照您的代码,我成功地编辑了属性,但似乎我需要关闭/重新启动我的 jupyter 内核才能看到更新的文件属性,否则我看不到该文件的任何属性。 ps.Commit() 之后是否有“关闭”文件的函数/方法?
    • @Bayes - 做ps = None
    • 谢谢你,@SimonMourier。我发现的下一个问题是如何在 propsys.SHGetPropertyStoreFromParsingName 函数中使用相对路径而不是绝对路径。我试过“.\\path\\myfile.jpg”,它引发了参数错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多