• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`plistlib` --- Generate and parse Apple ``.plist`` files
2=============================================================
3
4.. module:: plistlib
5   :synopsis: Generate and parse Apple 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 by Apple, primarily on macOS and iOS. This module supports both binary
21and XML plist files.
22
23The property list (``.plist``) file format is a simple serialization supporting
24basic object types, like dictionaries, lists, numbers and strings.  Usually the
25top level object is a dictionary.
26
27To write out and to parse a plist file, use the :func:`dump` and
28:func:`load` functions.
29
30To work with plist data in bytes objects, use :func:`dumps`
31and :func:`loads`.
32
33Values can be strings, integers, floats, booleans, tuples, lists, dictionaries
34(but only with string keys), :class:`bytes`, :class:`bytearray`
35or :class:`datetime.datetime` objects.
36
37.. versionchanged:: 3.4
38   New API, old API deprecated.  Support for binary format plists added.
39
40.. versionchanged:: 3.8
41   Support added for reading and writing :class:`UID` tokens in binary plists as used
42   by NSKeyedArchiver and NSKeyedUnarchiver.
43
44.. versionchanged:: 3.9
45   Old API removed.
46
47.. seealso::
48
49   `PList manual page <https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/>`_
50      Apple's documentation of the file format.
51
52
53This module defines the following functions:
54
55.. function:: load(fp, *, fmt=None, dict_type=dict)
56
57   Read a plist file. *fp* should be a readable and binary file object.
58   Return the unpacked root object (which usually is a
59   dictionary).
60
61   The *fmt* is the format of the file and the following values are valid:
62
63   * :data:`None`: Autodetect the file format
64
65   * :data:`FMT_XML`: XML file format
66
67   * :data:`FMT_BINARY`: Binary plist format
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, 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
127
128The following classes are available:
129
130.. class:: UID(data)
131
132   Wraps an :class:`int`.  This is used when reading or writing NSKeyedArchiver
133   encoded data, which contains UID (see PList manual).
134
135   It has one attribute, :attr:`data`, which can be used to retrieve the int value
136   of the UID.  :attr:`data` must be in the range ``0 <= data < 2**64``.
137
138   .. versionadded:: 3.8
139
140
141The following constants are available:
142
143.. data:: FMT_XML
144
145   The XML format for plist files.
146
147   .. versionadded:: 3.4
148
149
150.. data:: FMT_BINARY
151
152   The binary format for plist files
153
154   .. versionadded:: 3.4
155
156
157Examples
158--------
159
160Generating a plist::
161
162    pl = dict(
163        aString = "Doodah",
164        aList = ["A", "B", 12, 32.1, [1, 2, 3]],
165        aFloat = 0.1,
166        anInt = 728,
167        aDict = dict(
168            anotherString = "<hello & hi there!>",
169            aThirdString = "M\xe4ssig, Ma\xdf",
170            aTrueValue = True,
171            aFalseValue = False,
172        ),
173        someData = b"<binary gunk>",
174        someMoreData = b"<lots of binary gunk>" * 10,
175        aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
176    )
177    with open(fileName, 'wb') as fp:
178        dump(pl, fp)
179
180Parsing a plist::
181
182    with open(fileName, 'rb') as fp:
183        pl = load(fp)
184    print(pl["aKey"])
185