14.5.plistlib — Generate and parse Mac OS X.plist files

Source code:Lib/plistlib.py


This module provides an interface for reading and writing the “property list”files used mainly by Mac OS X and supports both binary and XML plist files.

The property list (.plist) file format is a simple serialization supportingbasic object types, like dictionaries, lists, numbers and strings. Usually thetop level object is a dictionary.

To write out and to parse a plist file, use thedump() andload() functions.

To work with plist data in bytes objects, usedumps()andloads().

Values can be strings, integers, floats, booleans, tuples, lists, dictionaries(but only with string keys),Data,bytes,bytesarrayordatetime.datetime objects.

Changed in version 3.4:New API, old API deprecated. Support for binary format plists added.

See also

PList manual page
Apple’s documentation of the file format.

This module defines the following functions:

plistlib.load(fp,*,fmt=None,use_builtin_types=True,dict_type=dict)

Read a plist file.fp should be a readable and binary file object.Return the unpacked root object (which usually is adictionary).

Thefmt is the format of the file and the following values are valid:

Ifuse_builtin_types is true (the default) binary data will be returnedas instances ofbytes, otherwise it is returned as instances ofData.

Thedict_type is the type used for dictionaries that are read from theplist file. The exact structure of the plist can be recovered by usingcollections.OrderedDict (although the order of keys shouldn’t beimportant in plist files).

XML data for theFMT_XML format is parsed using the Expat parserfromxml.parsers.expat – see its documentation for possibleexceptions on ill-formed XML. Unknown elements will simply be ignoredby the plist parser.

The parser for the binary format raisesInvalidFileExceptionwhen the file cannot be parsed.

New in version 3.4.

plistlib.loads(data,*,fmt=None,use_builtin_types=True,dict_type=dict)

Load a plist from a bytes object. Seeload() for an explanation ofthe keyword arguments.

New in version 3.4.

plistlib.dump(value,fp,*,fmt=FMT_XML,sort_keys=True,skipkeys=False)

Writevalue to a plist file.Fp should be a writable, binaryfile object.

Thefmt argument specifies the format of the plist file and can beone of the following values:

Whensort_keys is true (the default) the keys for dictionaries will bewritten to the plist in sorted order, otherwise they will be written inthe iteration order of the dictionary.

Whenskipkeys is false (the default) the function raisesTypeErrorwhen a key of a dictionary is not a string, otherwise such keys are skipped.

ATypeError will be raised if the object is of an unsupported type ora container that contains objects of unsupported types.

AnOverflowError will be raised for integer values that cannotbe represented in (binary) plist files.

New in version 3.4.

plistlib.dumps(value,*,fmt=FMT_XML,sort_keys=True,skipkeys=False)

Returnvalue as a plist-formatted bytes object. Seethe documentation fordump() for an explanation of the keywordarguments of this function.

New in version 3.4.

The following functions are deprecated:

plistlib.readPlist(pathOrFile)

Read a plist file.pathOrFile may be either a file name or a (readableand binary) file object. Returns the unpacked root object (which usuallyis a dictionary).

This function callsload() to do the actual work, see the documentationofthatfunction for an explanation of the keyword arguments.

Note

Dict values in the result have a__getattr__ method that defersto__getitem_. This means that you can use attribute access toaccess items of these dictionaries.

Deprecated since version 3.4:Useload() instead.

plistlib.writePlist(rootObject,pathOrFile)

WriterootObject to an XML plist file.pathOrFile may be either a file nameor a (writable and binary) file object

Deprecated since version 3.4:Usedump() instead.

plistlib.readPlistFromBytes(data)

Read a plist data from a bytes object. Return the root object.

Seeload() for a description of the keyword arguments.

Note

Dict values in the result have a__getattr__ method that defersto__getitem_. This means that you can use attribute access toaccess items of these dictionaries.

Deprecated since version 3.4:Useloads() instead.

plistlib.writePlistToBytes(rootObject)

ReturnrootObject as an XML plist-formatted bytes object.

Deprecated since version 3.4:Usedumps() instead.

The following classes are available:

Dict([dict]):

Return an extended mapping object with the same value as dictionarydict.

This class is a subclass ofdict where attribute access canbe used to access items. That is,aDict.key is the same asaDict['key'] for getting, setting and deleting items in the mapping.

Deprecated since version 3.0.

classplistlib.Data(data)

Return a “data” wrapper object around the bytes objectdata. This is usedin functions converting from/to plists to represent the<data> typeavailable in plists.

It has one attribute,data, that can be used to retrieve the Pythonbytes object stored in it.

Deprecated since version 3.4:Use abytes object instead.

The following constants are available:

plistlib.FMT_XML

The XML format for plist files.

New in version 3.4.

plistlib.FMT_BINARY

The binary format for plist files

New in version 3.4.

14.5.1. Examples

Generating a plist:

pl=dict(aString="Doodah",aList=["A","B",12,32.1,[1,2,3]],aFloat=0.1,anInt=728,aDict=dict(anotherString="<hello & hi there!>",aThirdString="M\xe4ssig, Ma\xdf",aTrueValue=True,aFalseValue=False,),someData=b"<binary gunk>",someMoreData=b"<lots of binary gunk>"*10,aDate=datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),)withopen(fileName,'wb')asfp:dump(pl,fp)

Parsing a plist:

withopen(fileName,'rb')asfp:pl=load(fp)print(pl["aKey"])