Skip to content Skip to sidebar Skip to footer

Read Tags of a File Python Mac Os

osxmetadata

Code style: black License: MIT All Contributors

What is osxmetadata?

osxmetadata provides a simple interface to admission various metadata about MacOS / OS X files. Currently supported metadata attributes include tags/keywords, Finder comments, authors, etc.

Motivation

Apple provides rich support for file metadata through diverse metadata extended attributes. MacOS provides tools to view and gear up these various metadata attributes. For example, mdls lists metadata associated with a file just doesn't let you edit the data while xattr allows the user to set extended attributes but requires the values be in the form of a MacOS plist which is impractical. osxmetadata makes information technology easy to to both view and dispense the MacOS metadata attributes, either programmatically or through a command line tool.

Supported operating systems

Only works on MacOS. Requires Python 3.7+.

Installation instructions

Installation using pipx

If you lot aren't familiar with installing python applications, I recommend you install osxmetadata with pipx. If you apply pipx, you lot will not need to create a virtual environs as pipx takes care of this. The easiest fashion to do this on a Mac is to utilize homebrew:

  • Open up Last (search for Terminal in Spotlight or look in Applications/Utilities)
  • Install homebrew according to instructions at https://mash.sh/
  • Type the following into Terminal: brew install pipx
  • Then blazon this: pipx install osxmetadata
  • Now you should be able to run osxmetadata by typing: osxmetadata

Once you've installed osxmetadata with pipx, to upgrade to the latest version:

Installation using pip

You can besides install directly from pypi:

Once you've installed osxmetadata with pip, to upgrade to the latest version:

              pip install --upgrade osxmetadata                          

Installation from git repository

OSXMetaData uses setuptools, thus merely run:

              git clone https://github.com/RhetTbull/osxmetadata.git cd osxmetadata  python3 setup.py install                          

I recommend y'all create a virtual environment before installing osxmetadata.

Command Line Usage

Installs control line tool called osxmetadata which provides a unproblematic interface to view/edit metadata supported by osxmetadata.

If you only intendance about the command line tool, I recommend installing with pipx

The command line tool tin can likewise be run via python -thou osxmetadata. Running information technology with no arguments or with --help pick volition print a help message:

              Usage: osxmetadata [OPTIONS] FILE    Read/write metadata from file(s).  Options:   -v, --version                   Show the version and exit.   -h, --assistance                      Testify this message and exit.   -w, --walk                      Walk directory tree, processing each file in                                   the tree.   -j, --json                      Impress output in JSON format, for employ with                                   --list and --go.   -X, --wipe                      Wipe all metadata attributes from FILE.   -s, --ready Attribute VALUE       Ready Aspect to VALUE.   -50, --list                      List all metadata attributes for FILE.   -c, --clear Attribute           Remove aspect from FILE.   -a, --append ATTRIBUTE VALUE    Append VALUE to Aspect.   -thousand, --go ATTRIBUTE             Get value of ATTRIBUTE.   -r, --remove ATTRIBUTE VALUE    Remove VALUE from Attribute; only applies to                                   multi-valued attributes.   -u, --update ATTRIBUTE VALUE    Update ATTRIBUTE with VALUE; for multi-                                   valued attributes, this adds VALUE to the                                   attribute if not already in the list.   -m, --mirror ATTRIBUTE1 ATTRIBUTE2                                   Mirror values between ATTRIBUTE1 and                                   ATTRIBUTE2 so that ATTRIBUTE1 = ATTRIBUTE2;                                   for multi-valued attributes, merges values;                                   for string attributes, sets ATTRIBUTE1 =                                   ATTRIBUTE2 overwriting whatever value in                                   ATTRIBUTE1.  For example: '--mirror keywords                                   tags' sets tags and keywords to same values.   -B, --backup                    Backup FILE attributes.  Backup file                                   '.osxmetadata.json' volition be created in aforementioned                                   folder equally FILE. Only backs upward attributes                                   known to osxmetadata unless used with --all.   -R, --restore                   Restore FILE attributes from backup file.                                   Restore volition look for backup file                                   '.osxmetadata.json' in aforementioned binder as FILE.                                   Merely restores attributes known to                                   osxmetadata unless used with --all.   -A, --all                       Process all extended attributes including                                   those not known to osxmetadata. Apply with                                   --backup/--restore to backup/restore all                                   extended attributes.   -V, --verbose                   Print verbose output.   -f, --copyfrom SOURCE_FILE      Copy attributes from file SOURCE_FILE.   --files-only                    Do non apply metadata commands to                                   directories themselves, only files in a                                   directory.   -p, --blueprint PATTERN           Only process files matching PATTERN; only                                   applies to --walk. If specified, but files                                   matching PATTERN volition exist processed equally each                                   directory is walked. May be used for than                                   once to specify multiple patterns. For                                   example, tag all *.pdf files in projectdir                                   and subfolders with tag 'project':                                   osxmetadata --append tags 'project' --walk                                   projectdir/ --pattern '*.pdf'  Valid attributes for ATTRIBUTE: Each aspect has a brusque name, a abiding name, and a long constant name. Any of these may be used for ATTRIBUTE  For example: --set findercomment "Hello world" or:          --set kMDItemFinderComment "Hello earth" or:          --prepare com.apple.metadata:kMDItemFinderComment "How-do-you-do earth"  Attributes that are strings can simply take i value for --set; --suspend will append to the existing value.  Attributes that are arrays can be set multiple times to add to the array: due east.g. --set keywords 'foo' --set keywords 'bar' will set keywords to ['foo', 'bar']  Options are executed in the following guild regardless of society passed on the control line: restore, wipe, copyfrom, clear, set, suspend, update, remove, mirror, go, list, backup.  --backup and --restore are mutually exclusive. Other options may exist combined or chained together.  Finder tags (tags attribute) comprise both a name and an optional color. To specify the color, append comma + colour proper noun (e.k. 'red') later the tag name. For example --prepare tags Foo,red. Valid color names are: gray, green, purple, bluish, yellowish, ruby, orange. If color is not specified but a tag of the same name has already been assigned a color in the Finder, the same colour will automatically be assigned.  com.apple.FinderInfo (finderinfo) value is a cardinal:value lexicon. To gear up finderinfo, pass value in format key1:value1,key2:value2,etc. For example: 'osxmetadata --set finderinfo color:2 file.ext'.  Brusk Name               Description authors                  kMDItemAuthors, com.apple.metadata:kMDItemAuthors;                          The writer, or authors, of the contents of the                          file.  A list of strings. comment                  kMDItemComment, com.apple tree.metadata:kMDItemComment;                          A comment related to the file.  This differs from                          the Finder comment, kMDItemFinderComment.  A                          cord. copyright                kMDItemCopyright,                          com.apple.metadata:kMDItemCopyright; The copyright                          owner of the file contents.  A string. creator                  kMDItemCreator, com.apple.metadata:kMDItemCreator;                          Application used to create the document content                          (for example "Word", "Pages", and then on).  A                          string. clarification              kMDItemDescription,                          com.apple.metadata:kMDItemDescription; A                          description of the content of the resources.  The                          description may include an abstract, tabular array of                          contents, reference to a graphical representation                          of content or a gratis-text account of the content.                          A string. downloadeddate           kMDItemDownloadedDate,                          com.apple.metadata:kMDItemDownloadedDate; The date                          the item was downloaded.  A date in ISO 8601                          format, time and timezone offset are optional: east.g.                          2020-04-14T12:00:00 (ISO 8601 w/o timezone),                          2020-04-fourteen (ISO 8601 west/o fourth dimension and time zone), or                          2020-04-14T12:00:00-07:00 (ISO 8601 with timezone                          outset). Times without timezone offset are assumed                          to exist in local timezone. duedate                  kMDItemDueDate, com.apple.metadata:kMDItemDueDate;                          The date the detail is due.  A date in ISO 8601                          format, fourth dimension and timezone kickoff are optional: e.g.                          2020-04-14T12:00:00 (ISO 8601 w/o timezone),                          2020-04-14 (ISO 8601 w/o fourth dimension and time zone), or                          2020-04-14T12:00:00-07:00 (ISO 8601 with timezone                          offset). Times without timezone offset are assumed                          to be in local timezone. findercolor              findercolor, com.apple tree.FinderInfo; Color tag set by                          the Finder.  Colors tin can also exist set by                          _kMDItemUserTags.  This is controlled by the Finder                          and it's recommended yous don't directly access this                          attribute.  If you set or remove a colour tag via                          _kMDItemUserTag, osxmetadata volition automatically                          handle processing of FinderInfo color tag. findercomment            kMDItemFinderComment,                          com.apple tree.metadata:kMDItemFinderComment; Finder                          comments for this file.  A string. finderinfo               finderinfo, com.apple.FinderInfo; Info set past the                          Finder, for example tag color.  Colors can also be                          gear up past _kMDItemUserTags.  com.apple.FinderInfo is                          controlled by the Finder and it's recommended you lot                          don't straight access this attribute.  If you gear up                          or remove a color tag via _kMDItemUserTag,                          osxmetadata will automatically handle processing of                          FinderInfo color tag. headline                 kMDItemHeadline,                          com.apple.metadata:kMDItemHeadline; A publishable                          entry providing a synopsis of the contents of the                          file.  A string. keywords                 kMDItemKeywords,                          com.apple.metadata:kMDItemKeywords; Keywords                          associated with this file. For example, "Birthday",                          "Important", etc. This differs from Finder tags                          (_kMDItemUserTags) which are keywords/tags shown in                          the Finder and searchable in Spotlight using                          "tag:tag_name".  A list of strings. osxphotos_detected_text  OSXPhotosDetectedText,                          osxphotos.metadata:detected_text; Text detected in                          a photo; used by osxphotos                          (https://github.com/RhetTbull/osxphotos). participants             kMDItemParticipants,                          com.apple.metadata:kMDItemParticipants; The list of                          people who are visible in an epitome or movie or                          written about in a document. A list of strings. projects                 kMDItemProjects,                          com.apple.metadata:kMDItemProjects; The listing of                          projects that this file is part of. For example, if                          you were working on a moving-picture show all of the files could                          be marked as belonging to the project "My Movie". A                          list of strings. rating                   kMDItemStarRating,                          com.apple.metadata:kMDItemStarRating; User rating                          of this item. For example, the stars rating of an                          iTunes track. An integer. stationary               kMDItemFSIsStationery,                          com.apple.metadata:kMDItemFSIsStationery; Boolean                          indicating if this file is stationery. Note: this                          is not what the Finder uses for Stationary Pad                          flag.  Encounter likewise 'stationarypad'. stationarypad            stationarypad, com.apple.FinderInfo; Marks the file                          equally stationary (a template that can be re-used).                          Setting this to Truthful is the same as checking the                          'Stationary Pad' box in Finder Info. subject                  kMDItemSubject, com.apple.metadata:kMDItemSubject;                          Subject of the this detail. A string. tags                     _kMDItemUserTags,                          com.apple.metadata:_kMDItemUserTags; Finder tags;                          searchable in Spotlight using "tag:tag_name".  If                          you desire tags/keywords visible in the Finder, employ                          this instead of kMDItemKeywords.  A list of Tag                          objects. title                    kMDItemTitle, com.apple.metadata:kMDItemTitle; The                          title of the file. For example, this could be the                          title of a document, the proper name of a song, or the                          subject of an email bulletin. A string. version                  kMDItemVersion, com.apple tree.metadata:kMDItemVersion;                          The version number of this file. A string. wherefroms               kMDItemWhereFroms,                          com.apple.metadata:kMDItemWhereFroms; Describes                          where the file was obtained from (due east.g. URL                          downloaded from).  A list of strings.                          

Supported Attributes

Information about commonly used MacOS metadata attributes is available from Apple.

osxmetadata currently supports the following metadata attributes:

Constant Brusk Name Long Constant Description
kMDItemAuthors authors com.apple.metadata:kMDItemAuthors The author, or authors, of the contents of the file. A list of strings.
kMDItemComment comment com.apple.metadata:kMDItemComment A comment related to the file. This differs from the Finder annotate, kMDItemFinderComment. A string.
kMDItemCopyright copyright com.apple.metadata:kMDItemCopyright The copyright possessor of the file contents. A cord.
kMDItemCreator creator com.apple.metadata:kMDItemCreator Application used to create the document content (for example "Give-and-take", "Pages", then on). A string.
kMDItemDescription description com.apple tree.metadata:kMDItemDescription A clarification of the content of the resource. The clarification may include an abstract, table of contents, reference to a graphical representation of content or a gratis-text account of the content. A string.
kMDItemDownloadedDate downloadeddate com.apple.metadata:kMDItemDownloadedDate The date the item was downloaded. A datetime.datetime object. If datetime.datetime object lacks tzinfo (i.eastward. it is timezone naive), it will be assumed to be in local timezone.
kMDItemDueDate duedate com.apple.metadata:kMDItemDueDate The appointment the particular is due. A datetime.datetime object. If datetime.datetime object lacks tzinfo (i.eastward. information technology is timezone naive), it will exist assumed to exist in local timezone.
findercolor findercolor com.apple.FinderInfo Color tag set by the Finder. Colors can as well be set by _kMDItemUserTags. This is controlled by the Finder and it's recommended you don't directly access this attribute. If you lot ready or remove a color tag via _kMDItemUserTag, osxmetadata volition automatically handle processing of FinderInfo color tag.
kMDItemFinderComment findercomment com.apple.metadata:kMDItemFinderComment Finder comments for this file. A string.
finderinfo finderinfo com.apple.FinderInfo Info set by the Finder, for example tag color. Colors tin likewise be fix by _kMDItemUserTags. com.apple tree.FinderInfo is controlled by the Finder and information technology'due south recommended yous don't directly access this attribute. If you set up or remove a color tag via _kMDItemUserTag, osxmetadata will automatically handle processing of FinderInfo color tag.
kMDItemHeadline headline com.apple.metadata:kMDItemHeadline A publishable entry providing a synopsis of the contents of the file. A string.
kMDItemKeywords keywords com.apple.metadata:kMDItemKeywords Keywords associated with this file. For example, "Altogether", "Important", etc. This differs from Finder tags (_kMDItemUserTags) which are keywords/tags shown in the Finder and searchable in Spotlight using "tag:tag_name". A listing of strings.
OSXPhotosDetectedText osxphotos_detected_text osxphotos.metadata:detected_text Text detected in a photograph; used past osxphotos (https://github.com/RhetTbull/osxphotos).
kMDItemParticipants participants com.apple.metadata:kMDItemParticipants The listing of people who are visible in an image or movie or written near in a document. A list of strings.
kMDItemProjects projects com.apple.metadata:kMDItemProjects The list of projects that this file is part of. For example, if y'all were working on a movie all of the files could exist marked as belonging to the project "My Movie". A listing of strings.
kMDItemStarRating rating com.apple.metadata:kMDItemStarRating User rating of this item. For example, the stars rating of an iTunes rail. An integer.
kMDItemFSIsStationery stationary com.apple.metadata:kMDItemFSIsStationery Boolean indicating if this file is stationery. Note: this is non what the Finder uses for Stationary Pad flag. See also 'stationarypad'.
stationarypad stationarypad com.apple.FinderInfo Marks the file as stationary (a template that can be re-used). Setting this to True is the same every bit checking the 'Stationary Pad' box in Finder Info.
kMDItemSubject subject com.apple tree.metadata:kMDItemSubject Subject of the this item. A string.
_kMDItemUserTags tags com.apple tree.metadata:_kMDItemUserTags Finder tags; searchable in Spotlight using "tag:tag_name". If you want tags/keywords visible in the Finder, utilise this instead of kMDItemKeywords. A list of Tag objects.
kMDItemTitle title com.apple.metadata:kMDItemTitle The championship of the file. For example, this could be the championship of a document, the name of a vocal, or the subject of an email message. A string.
kMDItemVersion version com.apple.metadata:kMDItemVersion The version number of this file. A string.
kMDItemWhereFroms wherefroms com.apple.metadata:kMDItemWhereFroms Describes where the file was obtained from (e.one thousand. URL downloaded from). A list of strings.

Example uses of the package

Using the command line tool to ready metadata:

Ready Finder tags to Examination, append "John Doe" to list of authors, clear (delete) description, prepare finder comment to "Hello World":

osxmetadata --set tags Test --append authors "John Doe" --clear clarification --set findercomment "Hello World" ~/Downloads/test.jpg

Set Finder tag Foo with color light-green:

osxmetadata --ready tags Foo,light-green test.txt

Walk a directory tree and add together the Finder tag "exam" to every file:

osxmetadata --suspend tags "Test" --walk ~/Downloads

Walk a directory tree and add together the Finder tag "project" to all .jpg and .pdf files:

osxmetadata --suspend tags "project" --walk projectdir --design "*.pdf" --design "*.jpg"

Using the programmatic interface

There are ii ways to admission metadata using the programmatic interface. First, an OSXMetaData object will create backdrop for each supported aspect using the "Short proper noun" in table in a higher place. For instance:

              from              osxmetadata              import              OSXMetaData,              Tag              filename              =              'foo.txt'              meta              =              OSXMetaData(filename)              # set description              meta.clarification              =              "This is my document."              # add "Foo" to tags              meta.tags              +=              [Tag("Foo")]              # set authors to "John Doe" and "Jane Smith"              meta.authors              =              ["John Doe","Jane Smith"]              # clear copyright              meta.copyright              =              None            

For additional details on using Finder tags, see Tag object.

If aspect is a list, most list methods can exist used. For example:

              >>              >              from              osxmetadata              import              OSXMetaData,              Tag              >>              >              md              =              OSXMetaData("test.txt")              >>              >              md.tags              [Tag('Blueish',              iv),              Tag('Green',              2),              Tag('Foo',              0)]              >>              >              medico.tags.pop(ane)              Tag('Light-green',              2)              >>              >              md.tags              [Tag('Blueish',              four),              Tag('Foo',              0)]              >>              >              md.tags.sort()              >>              >              md.tags              [Tag('Blue',              four),              Tag('Foo',              0)]              >>              >              md.tags.append(Tag("Test"))              >>              >              doctor.tags              [Tag('Blue',              4),              Tag('Foo',              0),              Tag('Exam',              0)]              >>              >              md.tags.extend([Tag("Test1"),Tag("Test2")])              >>              >              physician.tags              [Tag('Blue',              4),              Tag('Foo',              0),              Tag('Test',              0),              Tag('Test1',              0),              Tag('Test2',              0)]              >>              >              md.tags.remove(Tag("Blue",              four))              >>              >              md.tags              [Tag('Foo',              0),              Tag('Test',              0),              Tag('Test1',              0),              Tag('Test2',              0)]              >>              >              md.tags.remove(Tag("Blue",              4))              # ValueError if effort to remove element not in list              Traceback              (well-nigh              contempo              call              terminal):              File              "<stdin>",              line              1,              in              <              module              >              File              "/Users/rhet/anaconda3/envs/osxmeta/lib/python3.8/_collections_abc.py",              line              997,              in              remove              del              self[cocky.index(value)]              File              "/Users/rhet/anaconda3/envs/osxmeta/lib/python3.8/_collections_abc.py",              line              911,              in              index              raise              ValueError              ValueError              >>              >              md.tags.count(Tag("Exam"))              ane              >>              >              medico.tags.alphabetize(Tag("Test"))              1            

If aspect is a appointment/time stamp (east.g. kMDItemDownloadedDate), value should be a datetime.datetime object (or a list of datetime.datetime objects depending on the attribute type).

Note: datetime.datetime objects may be naive (lack timezone info, e.g. tzinfo=None) or timezone aware (take an associated timezone). If datetime.datetime object lacks timezone info, information technology will be assumed to exist local time. MacOS stores appointment values in extended attributes as UTC timestamps so all datetime.datetime objects will undergo appropriate conversion prior to writing to the extended attribute. See also tz_aware.

              >>              >              import              osxmetadata              >>              >              md              =              osxmetadata.OSXMetaData("/Users/rhet/Downloads/test.zip")              >>              >              physician.downloadeddate              [datetime.datetime(2020,              4,              14,              17,              51,              59,              40504)]              >>              >              at present              =              datetime.datetime.now()              >>              >              md.downloadeddate              =              at present              >>              >              dr..downloadeddate              [datetime.datetime(2020,              4,              15,              22,              17,              0,              558471)]

If aspect is cord, it can be treated as a standard python str:

              >>              >              import              osxmetadata              >>              >              md              =              osxmetadata.OSXMetaData("/Users/rhet/Downloads/test.jpg")              >>              >              physician.findercomment              =              "Hi world"              >>              >              md.findercomment              'Hello earth'              >>              >              doc.findercomment              +=              ". Farewell"              >>              >              md.findercomment              'Hello world. Adieu'              >>              >              "world"              in              md.findercomment              True            

The 2d way to access metadata is using methods from OSXMetaData to get/prepare/update etc. the various attributes. The diverse methods take the name of the aspect to be operated on which can exist specified using either the short name, abiding, or long constant from the table above. osxmetadata also exports constants with the same proper name as specified in the Apple tree documentation and the tabular array higher up, for example, kMDItemDescription.

              from osxmetadata import *  fname = 'foo.txt' meta = OSXMetaData(fname)  description = meta.get_attribute(kMDItemDescription)  meta.set_attribute(kMDItemCreator,"OSXMetaData")  meta.append_attribute("tags", [Tag("Blue")])  meta.update_attribute("com.apple.metadata:kMDItemKeywords",["Foo"])  meta.append_attribute("findercomment","Bye")  meta.clear_attribute("tags")                          

OSXMetaData methods and attributes

Create an OSXMetaData object

md = osxmetadata.OSXMetaData(filename, tz_aware = Faux)

  • filename: filename to operate on
  • tz_aware: (boolean, optional); if True, attributes which return datetime.datetime objects such as kMDItemDownloadedDate will return timezone aware datetime.datetime objects with timezone set to UTC; if False (default), will return timezone naive objects in user's local timezone. See also tz_aware.

Once created, the post-obit methods and attributes may be used to go/set metadata aspect information

proper noun

name()

Returns POSIX path of the file OSXMetaData is operating on.

get_attribute

get_attribute(attribute_name)

Load attribute and return value or None if attribute was not prepare (for list attributes, returns empty list if non set).

  • attribute_name: an osxmetadata Attribute name

get_attribute_str

get_attribute_str(attribute_name)

Returns a string representation of attribute value. e.g. if attribute is a datedate.datetime object, will format using datetime.isoformat()

  • attribute_name: an osxmetadata Attribute proper noun

set_attribute

set_attribute(attribute_name, value)

Write attribute to file with value

  • attribute_name: an osxmetadata Attribute name
  • value: value to store in aspect

update_attribute

update_attribute(attribute_name, value)

Update aspect with matrimony of itself and value. This avoids calculation duplicate values to attribute.

  • aspect: an osxmetadata Attribute name
  • value: value to append to aspect

Annotation: implementation simply calls append_attribute with update=True; provided for convenience.

append_attribute

append_attribute(attribute_name, value, update=False)

Append value to attribute.

  • attribute_name: an osxmetadata Attribute name
  • value: value to append to attribute
  • update: (bool) if True, update instead of suspend (e.yard. avoid adding duplicates, default is False)

remove_attribute

remove_attribute(attribute_name, value)

Remove a value from attribute, raise ValueError if attribute does non contain value. But applies to multi-valued attributes, otherwise raises TypeError.

  • attribute_name: name of OSXMetaData attribute

discard_attribute

discard_attribute(attribute_name, value)

Remove a value from attribute, unlike remove, does not raise exception if aspect does non contain value. Only applies to multi-valued attributes, otherwise raises TypeError.

  • attribute_name: name of OSXMetaData attribute

clear_attribute

clear_attribute(attribute_name)

Clear anttribute (remove it from the file).

  • attribute_name: name of OSXMetaData aspect

list_metadata

list_metadata()

List the Apple metadata attributes set on the file. e.g. those in com.apple.metadata namespace.

to_json

to_json()

Return dict in JSON format with all attributes for this file. Format is the same as used by the command line --fill-in/--restore functions.

asdict

asdict()

Returns a dictionary of attribute values for the lexicon object in form:

{'_version':              '0.99.6',              '_filepath':              '/Users/rhet/Desktop/t.txt',              '_filename':              't.txt',              'com.apple.metadata:_kMDItemUserTags': [['Hullo',              0]],              'com.apple.metadata:kMDItemComment':              'examination',              'com.apple.metadata:kMDItemFinderComment':              'Foo'}

tz_aware

tz_aware

Holding (boolean, default = False). If True, any attribute that returns a datetime.datetime object will return a timezone enlightened object. If False, datetime.datetime attributes will return timezone naive objects.

For example:

              >>              >              import              osxmetadata              >>              >              import              datetime              >>              >              md              =              osxmetadata.OSXMetaData("/Users/rhet/Downloads/exam.zip")              >>              >              md.downloadeddate              [datetime.datetime(2020,              iv,              14,              17,              51,              59,              40504)]              >>              >              now              =              datetime.datetime.now()              >>              >              doctor.downloadeddate              =              now              >>              >              doc.downloadeddate              [datetime.datetime(2020,              iv,              fifteen,              22,              17,              0,              558471)]              >>              >              dr..tz_aware              =              True              >>              >              md.downloadeddate              [datetime.datetime(2020,              iv,              16,              five,              17,              0,              558471,              tzinfo              =              datetime.timezone.utc)]              >>              >              utc              =              datetime.datetime.utcnow()              >>              >              utc              datetime.datetime(2020,              iv,              16,              5,              25,              ten,              635417)              >>              >              utc              =              utc.replace(tzinfo              =              datetime.timezone.utc)              >>              >              utc              datetime.datetime(2020,              4,              16,              v,              25,              10,              635417,              tzinfo              =              datetime.timezone.utc)              >>              >              md.downloadeddate              =              utc              >>              >              md.downloadeddate              [datetime.datetime(2020,              4,              16,              5,              25,              x,              635417,              tzinfo              =              datetime.timezone.utc)]              >>              >              md.tz_aware              =              False              >>              >              medico.downloadeddate              [datetime.datetime(2020,              4,              xv,              22,              25,              10,              635417)]

Tag object

Unlike other attributes, Finder tags (_kMDItemUserTags) have ii components: a name (str) and a color ID (unsigned int in range 0 to vii) represting a color tag in the Finder. Reading tags returns a list of Tag objects and setting tags requires a list of Tag objects.

Create a Tag object

Tag(name,colour)

  • name: tag proper noun (str)
  • color: optional; color ID for Finder colour label associated with tag (int)

If color is not provided, Tag volition see if the user has already assigned a color to a tag of the aforementioned name via the Finder (Finder | Preferences | Tags) and if so, assign the aforementioned color. If a match is non found, the tag will be created with no color (osxmetadata.FINDER_COLOR_NONE)

Valid color constants (exported by osxmetadata):

  • FINDER_COLOR_GRAY = 1
  • FINDER_COLOR_GREEN = 2
  • FINDER_COLOR_PURPLE = 3
  • FINDER_COLOR_BLUE = 4
  • FINDER_COLOR_YELLOW = 5
  • FINDER_COLOR_RED = 6
  • FINDER_COLOR_ORANGE = 7
              from              osxmetadata              import              OSXMetaData,              Tag,              FINDER_COLOR_GREEN              md              =              OSXMetaData("test.txt")              md.tags              =              [Tag("Foo")]              md.tags              +=              [Tag("Examination",FINDER_COLOR_GREEN)]

Usage Notes

Changes are immediately written to the file. For case, OSXMetaData.tags.append("Foo") immediately writes the tag 'Foo' to the file.

Metadata is refreshed from disk every fourth dimension a course property is accessed.

This will only work on file systems that back up Mac OS X extended attributes.

Dependencies

bitstring

Click

PyObjC

xattr

py-applescript

Related Projects

  • tag A control line tool to manipulate tags on Mac OS X files, and to query for files with those tags.
  • osx-tags Python module to dispense Finder tags in Os 10.

Acknowledgements

This module was inspired by osx-tags past "Ben S / scooby". I leveraged osx-tags to bootstrap the design of this module. I wanted a more general Os X metadata library and so I rolled my own. This module is published under the same MIT license as osx-tags.

Contributors

Cheers goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of whatever kind welcome!

mcleodsuat1995.blogspot.com

Source: https://github.com/RhetTbull/osxmetadata

Postar um comentário for "Read Tags of a File Python Mac Os"