Writing Metadata to a PSD file using Python

I want to save some tool specific information about a PSD file, but I don't want to have another pesky metadata file floating about to bloat my source texture folder.

Luckily, the PSD file format supports writing custom MetaData within it, which is perfect for what I want to do. In this particular example, I want my tool to be able to remember which folder the flattened image associated with this PSD will eventually be put into, the format the image will be in and the resolution.

There are many fields you can write to, but I have chosen to write to the Instructions information, because that just makes the most sense. Usually in Photoshop, you can see this fields available by going to the file info panel and going to the advanced tab:

In Python, we can access and write to the PSD's metadata very easily.

import win32com.client.dynamic as w32dynamic
w32 = w32dynamic.Dispatch

psApp = w32('Photoshop.Application')
doc = psApp.activeDocument

# When I pull this info out of the Metadata I split the | into
# a list of toolObjectName~setting pairs and then
# split these pairs into a tuple of strings (toolObjectName, setting)

settings = "chkBox_res_1024~True|export_dir~c:/test/my_doc.tga|rBtn_format_tga~True"

# Now to write this to the metadata
doc.Info.Instructions = settings

# If I want to get it back out...
settings = doc.Info.Instructions
print settings

I'm still experimenting with ways of storing the settings data in a prettier way, but so far this is working well for me, although the format and information I'm saving is *very* specific to the particular tool I am writing. Still early days... but hopefully the whole Metadata thing will be handy to other people out there.