getting and setting mac file and folder finder labels from Python

You can do this in python using the xattr module.

Here is an example, taken mostly from this question:

from xattr import xattr

colornames = {
    0: 'none',
    1: 'gray',
    2: 'green',
    3: 'purple',
    4: 'blue',
    5: 'yellow',
    6: 'red',
    7: 'orange',
}

attrs = xattr('./test.cpp')

try:
    finder_attrs = attrs['com.apple.FinderInfo']
    color = finder_attrs[9] >> 1 & 7
except KeyError:
    color = 0

print colornames[color]

Since I have colored this file with the red label, this prints 'red' for me. You can use the xattr module to also write a new label back to disk.


I don't know if this question is still relevant to anybody but there is a new package "mac-tag" that solves this issue.

pip install mac-tag

and then you have functions like:

function    __doc__
mac_tag.add(tags, path) # add tags to path(s)
mac_tag.find(tags, path=None)   # return a list of all paths with tags, limited to path(s) if present
mac_tag.get(path)   # return dict where keys are paths, values are lists of tags. equivalent of tag -l
mac_tag.match(tags, path)   # return a list of paths with with matching tags
mac_tag.parse_list_output(out)  # parse tag -l output and return dict
mac_tag.remove(tags, path)  # remove tags from path(s)
mac_tag.update(tags, path)  # set path(s) tags. equivalent of `tag -s

complete documentation at: https://pypi.org/project/mac-tag/


If you follow favoretti's link and then scroll down a bit, there's a link to https://github.com/danthedeckie/display_colors, which does this via xattr, but without the binary manipulations. I rewrote his code a bit:

from xattr import xattr

def set_label(filename, color_name):
    colors = ['none', 'gray', 'green', 'purple', 'blue', 'yellow', 'red', 'orange']
    key = u'com.apple.FinderInfo'
    attrs = xattr(filename)
    current = attrs.copy().get(key, chr(0)*32)
    changed = current[:9] + chr(colors.index(color_name)*2) + current[10:]
    attrs.set(key, changed)

set_label('/Users/chbrown/Desktop', 'green')