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

如何使用Python获取Windows 10系统的文件夹图标路径?

获取Windows 10文件夹图标路径的Python实现

Windows中自定义过图标的文件夹,会在其目录下生成隐藏的desktop.ini文件,图标路径就记录在这个文件里。以下是具体的实现步骤和代码:

核心思路

自定义文件夹的图标信息存储在desktop.ini的[.ShellClassInfo]节中,通常会有两个可能的键:

  • IconResource:格式为路径,索引(比如C:\icons\myicon.ico,0)
  • IconFile:直接指向图标文件路径

如果没有自定义图标,文件夹使用系统默认图标,路径一般是C:\Windows\system32\shell32.dll,对应不同的索引值(比如普通文件夹默认图标是索引3)。

Python代码实现

import os
import configparser

def get_folder_icon_path(folder_path):
    desktop_ini_path = os.path.join(folder_path, 'desktop.ini')
    icon_path = None

    # 检查desktop.ini是否存在
    if not os.path.exists(desktop_ini_path):
        # 返回系统默认图标路径(可根据需求调整)
        return r"C:\Windows\system32\shell32.dll"

    # 处理desktop.ini的编码(通常是UTF-16或ANSI)
    encodings = ['utf-16', 'ansi']
    config = configparser.ConfigParser()
    parsed = False

    for enc in encodings:
        try:
            with open(desktop_ini_path, 'r', encoding=enc) as f:
                config.read_file(f)
            parsed = True
            break
        except:
            continue

    if not parsed:
        return None

    # 读取图标路径
    if '.ShellClassInfo' in config:
        shell_section = config['.ShellClassInfo']
        if 'IconResource' in shell_section:
            # 拆分路径和索引,只保留路径部分
            icon_resource = shell_section['IconResource'].strip()
            icon_path = icon_resource.split(',')[0].strip('"')
        elif 'IconFile' in shell_section:
            icon_path = shell_section['IconFile'].strip('"')

        # 处理相对路径转绝对路径
        if icon_path and not os.path.isabs(icon_path):
            icon_path = os.path.abspath(os.path.join(folder_path, icon_path))

    return icon_path or r"C:\Windows\system32\shell32.dll"

# 示例使用
target_folder = r"C:\Your\Target\Folder"
icon_path = get_folder_icon_path(target_folder)
print(f"文件夹图标路径:{icon_path}")

注意事项

  • desktop.ini默认是隐藏+系统属性,确保Python进程有足够权限读取该文件
  • 部分系统保护文件夹的desktop.ini可能无法直接读取
  • 如果返回的是DLL/EXE文件(比如shell32.dll),图标是文件中的资源索引,若需要提取独立图标文件,可结合win32api相关工具处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:05:07