Posted By

IanMulvany on 02/12/08


Tagged

mac python applescript tags os x tag mdfind mdls tagbot


Versions (?)

switchTags.py


 / Published in: Python
 

Uses macs mdfind command to look for files that have spotlight comments, and then changes the comments in place. I used this to change the delimiter that I had been using to indicate a tag on my files. It applies the new tags via an applescript called from the command line.

  1. import os
  2.  
  3. # My tag delimiters
  4. old_delimiter = '#'
  5. new_delimiter = '&'
  6.  
  7. # Generate a piece of applescript that will take a POSIX file name
  8. # and add spotlight tags to this.
  9. # We will run this script using the osascript command in Mac OS X.
  10. def gen_add_comment_script(file,new_tags):
  11. temp_file = '"' + file + '"'
  12. osa_comment = '"' + " ".join(new_tags) + '"'
  13. osascript = """osascript<<END
  14. tell application "Finder"
  15. set filePath to POSIX file %s
  16. set fileComment to %s
  17. set the_File to filePath as alias
  18. set comment of the_File to fileComment
  19. end tell
  20. END""" % (temp_file, osa_comment)
  21.  
  22. return osascript
  23.  
  24. # get a list of files that include Spotlight comments that
  25. # have the old tag delimiter in them. Split the files into a list
  26. cmd = """ mdfind "kMDItemFinderComment = '*%s*'" """ % old_delimiter
  27. stdout_handle = os.popen(cmd, "r") # redirect stdout
  28. text = stdout_handle.read() # read stdout
  29. files = text.split("\n")
  30.  
  31. # Run through the list of files.
  32. # for each file do a mdls command and parse out the Spotlight comment as tags.
  33. # In each place where there is a tag with the old delimiter create a tag with the new delimiter.
  34. # Run the applescript to add these new tags to the file.
  35. for file in files:
  36. cmd = 'mdls ' + '"' + file + '"'
  37. stdout_handle = os.popen(cmd, "r")
  38. file_md = stdout_handle.read()
  39. md_items = file_md.split("\n")
  40. print file
  41. for md_item in md_items:
  42. if md_item.find("kMDItemFinderComment") > -1:
  43. tagline = md_item.split("=")[1]
  44. tagline = tagline.replace('"','')
  45. new_tagline = tagline.replace(old_delimiter,new_delimiter)
  46. old_tags = tagline.split()
  47. new_tags = new_tagline.split()
  48. script = gen_add_comment_script(file,new_tags)
  49. os.system(script)

Report this snippet  

You need to login to post a comment.