1:mod:`plistlib` --- Generate and parse Mac OS X ``.plist`` files
2================================================================
3
4.. module:: plistlib
5   :synopsis: Generate and parse Mac OS X plist files.
6
7.. moduleauthor:: Jack Jansen
8.. sectionauthor:: Georg Brandl <georg@python.org>
9.. (harvested from docstrings in the original file)
10
11**Source code:** :source:`Lib/plistlib.py`
12
13.. index::
14   pair: plist; file
15   single: property list
16
17--------------
18
19This module provides an interface for reading and writing the "property list"
20files used mainly by Mac OS X and supports both binary and XML plist files.
21
22The property list (``.plist``) file format is a simple serialization supporting
23basic object types, like dictionaries, lists, numbers and strings.  Usually the
24top level object is a dictionary.
25
26To write out and to parse a plist file, use the :func:`dump` and
27:func:`load` functions.
28
29To work with plist data in bytes objects, use :func:`dumps`
30and :func:`loads`.
31
32Values can be strings, integers, floats, booleans, tuples, lists, dictionaries
33(but only with string keys), :class:`Data`, :class:`bytes`, :class:`bytesarray`
34or :class:`datetime.datetime` objects.
35
36.. versionchanged:: 3.4
37   New API, old API deprecated.  Support for binary format plists added.
38
39.. versionchanged:: 3.8
40   Support added for reading and writing :class:`UID` tokens in binary plists as used
41   by NSKeyedArchiver and NSKeyedUnarchiver.
42
43.. seealso::
44
45   `PList manual page <https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/>`_
46      Apple's documentation of the file format.
47
48
49This module defines the following functions:
50
51.. function:: load(fp, *, fmt=None, use_builtin_types=True, dict_type=dict)
52
53   Read a plist file. *fp* should be a readable and binary file object.
54   Return the unpacked root object (which usually is a
55   dictionary).
56
57   The *fmt* is the format of the file and the following values are valid:
58
59   * :data:`None`: Autodetect the file format
60
61   * :data:`FMT_XML`: XML file format
62
63   * :data:`FMT_BINARY`: Binary plist format
64
65   If *use_builtin_types* is true (the default) binary data will be returned
66   as instances of :class:`bytes`, otherwise it is returned as instances of
67   :class:`Data`.
68
69   The *dict_type* is the type used for dictionaries that are read from the
70   plist file.
71
72   XML data for the :data:`FMT_XML` format is parsed using the Expat parser
73   from :mod:`xml.parsers.expat` -- see its documentation for possible
74   exceptions on ill-formed XML.  Unknown elements will simply be ignored
75   by the plist parser.
76
77   The parser for the binary format raises :exc:`InvalidFileException`
78   when the file cannot be parsed.
79
80   .. versionadded:: 3.4
81
82
83.. function:: loads(data, *, fmt=None, use_builtin_types=True, dict_type=dict)
84
85   Load a plist from a bytes object. See :func:`load` for an explanation of
86   the keyword arguments.
87
88   .. versionadded:: 3.4
89
90
91.. function:: dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
92
93   Write *value* to a plist file. *Fp* should be a writable, binary
94   file object.
95
96   The *fmt* argument specifies the format of the plist file and can be
97   one of the following values:
98
99   * :data:`FMT_XML`: XML formatted plist file
100
101   * :data:`FMT_BINARY`: Binary formatted plist file
102
103   When *sort_keys* is true (the default) the keys for dictionaries will be
104   written to the plist in sorted order, otherwise they will be written in
105   the iteration order of the dictionary.
106
107   When *skipkeys* is false (the default) the function raises :exc:`TypeError`
108   when a key of a dictionary is not a string, otherwise such keys are skipped.
109
110   A :exc:`TypeError` will be raised if the object is of an unsupported type or
111   a container that contains objects of unsupported types.
112
113   An :exc:`OverflowError` will be raised for integer values that cannot
114   be represented in (binary) plist files.
115
116   .. versionadded:: 3.4
117
118
119.. function:: dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
120
121   Return *value* as a plist-formatted bytes object. See
122   the documentation for :func:`dump` for an explanation of the keyword
123   arguments of this function.
124
125   .. versionadded:: 3.4
126
127The following functions are deprecated:
128
129.. function:: readPlist(pathOrFile)
130
131   Read a plist file. *pathOrFile* may be either a file name or a (readable
132   and binary) file object. Returns the unpacked root object (which usually
133   is a dictionary).
134
135   This function calls :func:`load` to do the actual work, see the documentation
136   of :func:`that function <load>` for an explanation of the keyword arguments.
137
138   .. deprecated:: 3.4 Use :func:`load` instead.
139
140   .. versionchanged:: 3.7
141      Dict values in the result are now normal dicts.  You no longer can use
142      attribute access to access items of these dictionaries.
143
144
145.. function:: writePlist(rootObject, pathOrFile)
146
147   Write *rootObject* to an XML plist file. *pathOrFile* may be either a file name
148   or a (writable and binary) file object
149
150   .. deprecated:: 3.4 Use :func:`dump` instead.
151
152
153.. function:: readPlistFromBytes(data)
154
155   Read a plist data from a bytes object.  Return the root object.
156
157   See :func:`load` for a description of the keyword arguments.
158
159   .. deprecated:: 3.4 Use :func:`loads` instead.
160
161   .. versionchanged:: 3.7
162      Dict values in the result are now normal dicts.  You no longer can use
163      attribute access to access items of these dictionaries.
164
165
166.. function:: writePlistToBytes(rootObject)
167
168   Return *rootObject* as an XML plist-formatted bytes object.
169
170   .. deprecated:: 3.4 Use :func:`dumps` instead.
171
172
173The following classes are available:
174
175.. class:: Data(data)
176
177   Return a "data" wrapper object around the bytes object *data*.  This is used
178   in functions converting from/to plists to represent the ``<data>`` type
179   available in plists.
180
181   It has one attribute, :attr:`data`, that can be used to retrieve the Python
182   bytes object stored in it.
183
184   .. deprecated:: 3.4 Use a :class:`bytes` object instead.
185
186.. class:: UID(data)
187
188   Wraps an :class:`int`.  This is used when reading or writing NSKeyedArchiver
189   encoded data, which contains UID (see PList manual).
190
191   It has one attribute, :attr:`data`, which can be used to retrieve the int value
192   of the UID.  :attr:`data` must be in the range `0 <= data < 2**64`.
193
194   .. versionadded:: 3.8
195
196
197The following constants are available:
198
199.. data:: FMT_XML
200
201   The XML format for plist files.
202
203   .. versionadded:: 3.4
204
205
206.. data:: FMT_BINARY
207
208   The binary format for plist files
209
210   .. versionadded:: 3.4
211
212
213Examples
214--------
215
216Generating a plist::
217
218    pl = dict(
219        aString = "Doodah",
220        aList = ["A", "B", 12, 32.1, [1, 2, 3]],
221        aFloat = 0.1,
222        anInt = 728,
223        aDict = dict(
224            anotherString = "<hello & hi there!>",
225            aThirdString = "M\xe4ssig, Ma\xdf",
226            aTrueValue = True,
227            aFalseValue = False,
228        ),
229        someData = b"<binary gunk>",
230        someMoreData = b"<lots of binary gunk>" * 10,
231        aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
232    )
233    with open(fileName, 'wb') as fp:
234        dump(pl, fp)
235
236Parsing a plist::
237
238    with open(fileName, 'rb') as fp:
239        pl = load(fp)
240    print(pl["aKey"])
241