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.. seealso::
40
41   `PList manual page <https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/>`_
42      Apple's documentation of the file format.
43
44
45This module defines the following functions:
46
47.. function:: load(fp, \*, fmt=None, use_builtin_types=True, dict_type=dict)
48
49   Read a plist file. *fp* should be a readable and binary file object.
50   Return the unpacked root object (which usually is a
51   dictionary).
52
53   The *fmt* is the format of the file and the following values are valid:
54
55   * :data:`None`: Autodetect the file format
56
57   * :data:`FMT_XML`: XML file format
58
59   * :data:`FMT_BINARY`: Binary plist format
60
61   If *use_builtin_types* is true (the default) binary data will be returned
62   as instances of :class:`bytes`, otherwise it is returned as instances of
63   :class:`Data`.
64
65   The *dict_type* is the type used for dictionaries that are read from the
66   plist file.
67
68   XML data for the :data:`FMT_XML` format is parsed using the Expat parser
69   from :mod:`xml.parsers.expat` -- see its documentation for possible
70   exceptions on ill-formed XML.  Unknown elements will simply be ignored
71   by the plist parser.
72
73   The parser for the binary format raises :exc:`InvalidFileException`
74   when the file cannot be parsed.
75
76   .. versionadded:: 3.4
77
78
79.. function:: loads(data, \*, fmt=None, use_builtin_types=True, dict_type=dict)
80
81   Load a plist from a bytes object. See :func:`load` for an explanation of
82   the keyword arguments.
83
84   .. versionadded:: 3.4
85
86
87.. function:: dump(value, fp, \*, fmt=FMT_XML, sort_keys=True, skipkeys=False)
88
89   Write *value* to a plist file. *Fp* should be a writable, binary
90   file object.
91
92   The *fmt* argument specifies the format of the plist file and can be
93   one of the following values:
94
95   * :data:`FMT_XML`: XML formatted plist file
96
97   * :data:`FMT_BINARY`: Binary formatted plist file
98
99   When *sort_keys* is true (the default) the keys for dictionaries will be
100   written to the plist in sorted order, otherwise they will be written in
101   the iteration order of the dictionary.
102
103   When *skipkeys* is false (the default) the function raises :exc:`TypeError`
104   when a key of a dictionary is not a string, otherwise such keys are skipped.
105
106   A :exc:`TypeError` will be raised if the object is of an unsupported type or
107   a container that contains objects of unsupported types.
108
109   An :exc:`OverflowError` will be raised for integer values that cannot
110   be represented in (binary) plist files.
111
112   .. versionadded:: 3.4
113
114
115.. function:: dumps(value, \*, fmt=FMT_XML, sort_keys=True, skipkeys=False)
116
117   Return *value* as a plist-formatted bytes object. See
118   the documentation for :func:`dump` for an explanation of the keyword
119   arguments of this function.
120
121   .. versionadded:: 3.4
122
123The following functions are deprecated:
124
125.. function:: readPlist(pathOrFile)
126
127   Read a plist file. *pathOrFile* may be either a file name or a (readable
128   and binary) file object. Returns the unpacked root object (which usually
129   is a dictionary).
130
131   This function calls :func:`load` to do the actual work, see the documentation
132   of :func:`that function <load>` for an explanation of the keyword arguments.
133
134   .. deprecated:: 3.4 Use :func:`load` instead.
135
136   .. versionchanged:: 3.7
137      Dict values in the result are now normal dicts.  You no longer can use
138      attribute access to access items of these dictionaries.
139
140
141.. function:: writePlist(rootObject, pathOrFile)
142
143   Write *rootObject* to an XML plist file. *pathOrFile* may be either a file name
144   or a (writable and binary) file object
145
146   .. deprecated:: 3.4 Use :func:`dump` instead.
147
148
149.. function:: readPlistFromBytes(data)
150
151   Read a plist data from a bytes object.  Return the root object.
152
153   See :func:`load` for a description of the keyword arguments.
154
155   .. deprecated:: 3.4 Use :func:`loads` instead.
156
157   .. versionchanged:: 3.7
158      Dict values in the result are now normal dicts.  You no longer can use
159      attribute access to access items of these dictionaries.
160
161
162.. function:: writePlistToBytes(rootObject)
163
164   Return *rootObject* as an XML plist-formatted bytes object.
165
166   .. deprecated:: 3.4 Use :func:`dumps` instead.
167
168
169The following classes are available:
170
171.. class:: Data(data)
172
173   Return a "data" wrapper object around the bytes object *data*.  This is used
174   in functions converting from/to plists to represent the ``<data>`` type
175   available in plists.
176
177   It has one attribute, :attr:`data`, that can be used to retrieve the Python
178   bytes object stored in it.
179
180   .. deprecated:: 3.4 Use a :class:`bytes` object instead.
181
182
183The following constants are available:
184
185.. data:: FMT_XML
186
187   The XML format for plist files.
188
189   .. versionadded:: 3.4
190
191
192.. data:: FMT_BINARY
193
194   The binary format for plist files
195
196   .. versionadded:: 3.4
197
198
199Examples
200--------
201
202Generating a plist::
203
204    pl = dict(
205        aString = "Doodah",
206        aList = ["A", "B", 12, 32.1, [1, 2, 3]],
207        aFloat = 0.1,
208        anInt = 728,
209        aDict = dict(
210            anotherString = "<hello & hi there!>",
211            aThirdString = "M\xe4ssig, Ma\xdf",
212            aTrueValue = True,
213            aFalseValue = False,
214        ),
215        someData = b"<binary gunk>",
216        someMoreData = b"<lots of binary gunk>" * 10,
217        aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
218    )
219    with open(fileName, 'wb') as fp:
220        dump(pl, fp)
221
222Parsing a plist::
223
224    with open(fileName, 'rb') as fp:
225        pl = load(fp)
226    print(pl["aKey"])
227