You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python/Windows CMD获取图片Rating属性以查找收藏图片?

获取Windows收藏图片(Rating属性)的方法

一、Windows PowerShell方法

CMD本身无法直接访问Shell扩展属性,推荐用PowerShell实现:

# 替换为你的图片目录
$targetDir = "C:\Your\Image\Directory"
$shell = New-Object -ComObject Shell.Application
$folder = $shell.Namespace($targetDir)

# 遍历目录下所有文件
foreach ($item in $folder.Items()) {
    # 获取System.Rating属性值(0=无星,1=一星,25=二星,50=三星,75=四星,99=五星)
    $rating = $item.ExtendedProperty("System.Rating")
    # 筛选至少一颗星的图片
    if ($null -ne $rating -and $rating -ge 1) {
        Write-Output $item.Path
    }
}

说明:

  • System.Rating是Windows系统定义的收藏星对应属性,取值范围0-99,只要值≥1就代表已标记为收藏。
  • 如果遇到属性无法读取的情况,可以先遍历属性索引确认Rating的对应位置:
    $folder = $shell.Namespace("C:\Test")
    for ($i=0; $i -lt 300; $i++) {
        $propName = $folder.GetDetailsOf($folder.Items(), $i)
        if ($propName -eq "Rating") { Write-Host "Rating索引:$i" }
    }
    
    之后用$folder.GetDetailsOf($item, 索引值)替代ExtendedProperty方法即可。

二、Python方法

Python的os.stat只能获取文件系统基础属性,需要借助pywin32库访问Windows Shell对象来获取Rating属性:

步骤1:安装依赖

pip install pywin32

步骤2:代码实现

import win32com.client
import os

def get_rating(file_path):
    """获取单个文件的System.Rating属性值"""
    shell = win32com.client.Dispatch("Shell.Application")
    folder_path, filename = os.path.split(file_path)
    folder = shell.Namespace(folder_path)
    item = folder.ParseName(filename)
    
    # 自动获取Rating属性的索引(适配不同Windows版本)
    rating_index = None
    for i in range(300):
        prop_name = folder.GetDetailsOf(folder.Items(), i)
        if prop_name == "Rating":
            rating_index = i
            break
    if not rating_index:
        return 0
    
    rating_str = folder.GetDetailsOf(item, rating_index)
    return int(rating_str) if rating_str.isdigit() else 0

def find_favorited_images(root_dir):
    """遍历目录,返回所有标记为收藏的图片路径"""
    favorited = []
    image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff')
    
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.lower().endswith(image_extensions):
                file_path = os.path.join(dirpath, filename)
                rating = get_rating(file_path)
                if rating >= 1:
                    favorited.append(file_path)
    return favorited

# 调用示例
if __name__ == "__main__":
    target_directory = r"C:\Your\Image\Directory"
    result = find_favorited_images(target_directory)
    for img_path in result:
        print(img_path)

说明:

  • 代码会自动适配不同Windows版本的属性索引位置,避免因系统差异导致的读取失败。
  • System.Rating值≥1即表示图片被标记为收藏(一星及以上)。
  • 仅支持Windows系统,因为依赖Windows Shell COM对象。

为什么WMIC和os.stat无法获取Rating?

  • WMIC:只能查询WMI提供的系统级文件属性,不包含Windows Shell扩展的用户收藏类属性。
  • os.stat:仅读取文件系统的元数据(如创建时间、文件大小等),无法访问Windows特有的Shell扩展属性。

内容的提问来源于stack exchange,提问作者KRM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:03:40