How can I add OS X “tags” to files programmatically?

前端 未结 9 1625
轻奢々
轻奢々 2021-01-29 22:23

Since Mavericks, OS X has had the ability to tag & colour files in Finder.

\"finder

Is there any

9条回答
  •  你的背包
    2021-01-29 22:36

    This does not cover tags, but for changing label colors, one way to do it is through a command like this:

    xattr -wx com.apple.FinderInfo \
    0000000000000000000400000000000000000000000000000000000000000000 myfile.txt
    

    The 04 buried in the middle is setting the file color.

    Here is a python script which wraps that command lets you set the tag color on a file or series of files:

    import sys
    import subprocess
    
    def colorizeFile(ColorName,FileName):
        ReverseTable = {
             "clear"  :  "01",
             "gray"   :  "03",
             "green"  :  "04",
             "purple" :  "06",
             "blue"   :  "09",
             "yellow" :  "0A",
             "red"    :  "0C",
             "orange" :  "0E",
             "c"      :  "01",
             "a"      :  "03",
             "g"      :  "04",
             "p"      :  "06",
             "b"      :  "09",
             "y"      :  "0A",
             "r"      :  "0C",
             "o"      :  "0E",
        }
    
        HexString = 18*"0" + ReverseTable.get(ColorName) + 44*"0"
        Xcommand = 'xattr -wx com.apple.FinderInfo {0} {1}'.format(HexString,FileName)
        ProcString = subprocess.check_call(Xcommand, stderr=subprocess.STDOUT,shell=True) 
    
    if __name__ == "__main__":
        if len(sys.argv)<3:
            sys.stderr.write(__doc__.format(sys.argv[0]))
        else:
            Cname = sys.argv[1]
            Flist = sys.argv[2:]
            for File in Flist:
                colorizeFile(Cname.lower(),File)
            sys.stderr.write("## Colorized {0} file(s) as {1}\n".format(len(Flist),Cname)) 
    

    Usage is:

      labelcolor.py [color] *.jpg
    

    where [color] is a name or abbreviation as defined below:

        clear (c), grAy (a), green (g), purple (p), 
        blue (b), yellow (y), red (r), orange (o)
    

提交回复
热议问题