Search code examples
pythonmacosfinder

getting and setting mac file and folder finder labels from Python


I have been trying to find out how to get and set the colour of file labels from python.

The closest thing I've found to a solution was this, but I can't seem to find the module macfile anywhere. Am I just not looking hard enough?

Is there a different way to achieve this if not?


Solution

  • 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.