Suppose you have this folder:

Notice that some files have multiple tags. One tag is Work
which is a custom tag.
There are three ways that I have used to get the Finder tags into Python.
First, use xattr
to generate a binary plist
of extended attributes from the key 'com.apple.metadata:_kMDItemUserTags'
and then convert that to a list with plistlib:
import xattr
import plistlib
def get_tags_xattr(fn):
try:
bpl=xattr.getxattr(fn, 'com.apple.metadata:_kMDItemUserTags')
rtr=[e.partition('\n')[0]
for e in plistlib.loads(bpl, fmt=plistlib.FMT_BINARY)]
return rtr if rtr else None
except OSError:
return None
The second is to use the program tag which can be installed with brew
:
from subprocess import run, PIPE
def get_tags_tag(fn):
if 'com.apple.metadata:_kMDItemUserTags' in xattr.listxattr(fn):
rtr=run(['tag', '-g', '--no-name', fn],
stdout=PIPE).stdout.decode('utf-8').splitlines()
return rtr if rtr else None
return None
The third is to use the PyPi module osxmetadata:
import osxmetadata
def get_tags_osxmeta(fn):
tags=[t.name for t in osxmetadata.OSXMetaData(fn).tags]
if tags:
return tags
return None
Here is a demo of all three:
from pathlib import Path
p=Path('/tmp/test')
for fn in (fn for fn in p.glob('*') if fn.is_file()):
print(fn, get_tags_osxmeta(fn),
get_tags_tag(fn),
get_tags_xattr(fn))
Prints on that sample folder:
/tmp/test/DSC_2930-m.jpg ['Red', 'Green'] ['Green', 'Red'] ['Red', 'Green']
/tmp/test/DSC_2929.JPG None None None
/tmp/test/DSC_2939.JPG None None None
/tmp/test/DSC_2938.JPG ['Red'] ['Red'] ['Red']
/tmp/test/DSC_2937.JPG None None None
/tmp/test/DSC_2942-m.jpg ['Red', 'Orange', 'Gray', 'Work'] ['Gray', 'Orange', 'Red', 'Work'] ['Red', 'Orange', 'Gray', 'Work']
/tmp/test/DSC_2934.JPG ['Red'] ['Red'] ['Red']
/tmp/test/DSC_2930.JPG None None None
/tmp/test/DSC_2931.JPG None None None
/tmp/test/DSC_2933.JPG None None None
/tmp/test/DSC_2932.JPG ['Red'] ['Red'] ['Red']
/tmp/test/DSC_2941.JPG None None None
/tmp/test/DSC_2942.JPG None None None
The best of those (that which I use most often) is the osxmetadata module. It is fast and very flexible. If you just need the tags, the other ways work well too. The first is likely the fastest.