tags:

views:

604

answers:

2

Hello Pythonistas,

I need to read and serialize objects from and to XML, Apple's .plist format in particular. What's the most intelligent way to do it in Python? Are there any ready-made solutions?

+5  A: 

Check out plistlib.

Hank Gay
+1  A: 

Assuming you are on a Mac, you can use PyObjC.

Here is an example of reading from a plist, from Using Python For System Administration, slide 27.

from Cocoa import NSDictionary

myfile = "/Library/Preferences/com.apple.SoftwareUpdate.plist"
mydict = NSDictionary.dictionaryWithContentsOfFile_(myfile)

print mydict["LastSuccessfulDate"]

# returns: 2009-08-11 08:38:01 -0600

And an example of writing to a plist (that I wrote):

#!/usr/bin/env python

from Cocoa import NSDictionary, NSString

myfile = "~/test.plist"
myfile = NSString.stringByExpandingTildeInPath(myfile)

mydict = {"Nice Number" : 47, "Universal Sum" : 42}
mydict["Vector"] = (10, 20, 30)
mydict["Complex"] = [47, "i^2"]
mydict["Truth"] = True

NSDictionary.dictionaryWithDictionary_(mydict).writeToFile_atomically_(myfile, True)

When I then run defaults read ~/test in bash, I get:

{
    Complex =     (
        47,
        "i^2"
    );
    "Nice Number" = 47;
    Truth = 1;
    "Universal Sum" = 42;
    Vector =     (
        10,
        20,
        30
    );
}

And the file looks very nice when opened in Property List Editor.app.

Clinton Blackmore