如何通过Python自定义文件夹的图标?

时间:2014-11-06 09:41:18

标签: python windows desktop.ini

正如this SU answer所述,为了更改文件夹的图标,必须将文件夹的属性更改为只读或系统,并使其desktop.ini包含

之类的东西
[.ShellClassInfo]
IconResource=somePath.dll,0

虽然使用win32api.SetFileAttributes(dirpath, win32con.FILE_ATTRIBUTE_READONLY)并从头开始创建desktop.ini会很简单,但我希望保留可能存在的desktop.ini中存在的其他自定义设置。但是我应该使用ConfigParser吗? win32api(或者ctypes.win32)提供本地方法吗?

1 个答案:

答案 0 :(得分:1)

好的,所以从this thread开始,我成功了。我希望它会对你有所帮助。

这是我的基本desktop.ini文件:

[.ShellClassInfo]
IconResource=somePath.dll,0

[Fruits]
Apple = Blue
Strawberry = Pink

[Vegies]
Potatoe = Green
Carrot = Orange

[RandomClassInfo]
foo = somePath.ddsll,0

这是我使用的脚本:

from ConfigParser import RawConfigParser

dict = {"Fruits":{"Apple":"Green", "Strawberry":"Red"},"Vegies":{"Carrot":"Orange"}  }
# Get a config object
config = RawConfigParser()
# Read the file 'desktop.ini'
config.read(r'C:\Path\To\desktop.ini')

for section in dict.keys():
    for option in dict[section]:
        try:
            # Read the value from section 'Fruit', option 'Apple'
            currentVal = config.get( section, option )
            print "Current value of " + section + " - " + option + ": " + currentVal
            # If the value is not the right one
            if currentVal != dict[section][option]:
                print "Replacing value of " + section + " - " + option + ": " + dict[section][option]
                # Then we set the value to 'Llama'
                config.set( section, option, dict[section][option])
        except:
            print "Could not find " + section + " - " + option 

# Rewrite the configuration to the .ini file
with open(r'C:\Path\To\desktop.ini', 'w') as myconfig:
    config.write(myconfig)

这是输出desktop.ini文件:

[.ShellClassInfo]
iconresource = somePath.dll,0

[Fruits]
apple = Green
strawberry = Red

[Vegies]
potatoe = Green
carrot = Orange

[RandomClassInfo]
foo = somePath.ddsll,0

我遇到的唯一问题是选项丢失了他们的第一个大写字母。