Tobias Kienzler
Tobias Kienzler

Reputation: 27415

How to customize a folder's icon via Python?

As this SU answer notes, in order to change a folder's icon, one has to change a folder's attribute to read-only or system, and have its desktop.ini contain something like

[.ShellClassInfo]
IconResource=somePath.dll,0

While it would be straightforward to use win32api.SetFileAttributes(dirpath, win32con.FILE_ATTRIBUTE_READONLY) and create the desktop.ini from scratch, I'd like to preserve other customizations present in a potentially existing desktop.ini. But should I use ConfigParser for that or does e.g. win32api (or maybe ctypes.win32) provide native means to do so?

Upvotes: 3

Views: 2479

Answers (1)

DrHaze
DrHaze

Reputation: 1318

Ok, so from this thread, I managed to get something working. I hope that it will help you.

Here is my base desktop.ini file:

[.ShellClassInfo]
IconResource=somePath.dll,0

[Fruits]
Apple = Blue
Strawberry = Pink

[Vegies]
Potatoe = Green
Carrot = Orange

[RandomClassInfo]
foo = somePath.ddsll,0

Here is the script I use:

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)

Here is the output desktop.ini file:

[.ShellClassInfo]
iconresource = somePath.dll,0

[Fruits]
apple = Green
strawberry = Red

[Vegies]
potatoe = Green
carrot = Orange

[RandomClassInfo]
foo = somePath.ddsll,0

The only problem I have is that the options are loosing their first letter uppercase.

Upvotes: 1

Related Questions