How can I set Spotlight metadata to files?
Solution 1:
I don't think there's a way to -- the Spotlight indexes are generated by metadata importers that scan files and figure out their properties. If the relevant importer doesn't detect some property, then as far as Spotlight is concerned it doesn't exist.
Now, it might be possible to change the actual file in such a way as to add properties to its index entry. This page claims you can add extended attributes starting with "com.apple.metadata:" and they'll be added to the spotlight entry for the file, but I couldn't get it to work. The SpotMeta project extends the import system to add extended attributes to the spotlight database, but only works on OS X v10.4. Not an actual solution, but that's as close as I could find...
Solution 2:
You can always use the command line tool xattr
, which lists/reads/writes/erases the filesystem's extended attributes of a file.
That's what spotlight uses to build it's index.
Note that spotlight information keys are prefixed with com.apple.metadata:
As quick example, to change the display name on spotlight of a file:
xattr -w com.apple.metadata:kMDItemDisplayName MyNewFilename.txt ActualFile.txt
to access xattr help, type on t:
xattr -h
Solution 3:
Here is a Python function I use to write Finder Comments to a file using the system shell. They show up in Spotlight, but not in the Get Info box...
def writexattrs(F,TagList):
import subprocess
""" writexattrs(F,TagList):
Writes the list of tags to xattr field of file named F
"""
plistFront = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><array>'
plistEnd = '</array></plist>'
plistTagString = ''
for Tag in TagList:
plistTagString = plistTagString + '<string>{}</string>'.format(Tag)
TagText = plistFront + plistTagString + plistEnd
WhichAttribute = "com.apple.metadata:kMDItemFinderComment"
# Other attributes you might want to try: ["kOMUserTags","kMDItemOMUserTags","_kMDItemUserTags","kMDItemkeywords"]
XattrCommand = 'xattr -w {0} \'{1}\' "{2}"'.format(WhichAttribute,TagText.encode("utf8"),F)
# optional, print command format to check:
# print XattrCommand
ProcString = subprocess.check_output(XattrCommand, stderr=subprocess.STDOUT,shell=True)
return ProcString