xml processing

Magnus Lycka lycka at carmen.se
Wed Jun 1 15:51:06 CEST 2005


Jeff Elkins wrote:
> I've like to use python to maintain a small addressbook which lives on a Sharp 
> Zaurus. This list will never grow beyond 200 or so entries. I've installed 
> pyxml.
> 
> Speaking generally, given a wxpython app to do data entry, 
> I'm planning to:
> 
> 1. parse the addressbook file, loading its data into an array.
> 2. Perform any edit operations within the array.
> 3. Write out a finished xml file from the array when I'm done.
> 
> Is this reasonable? Better, smarter ways to accomplish this?

Why XML?

I guess the simplest solution whould be to use pickle.

Saving:
 >>> import pickle
 >>> l = []
 >>> l.append(('Alan', '1st Street', 123456))
 >>> l.append(('Ben', '2nd Street', 234567))
 >>> l.append(('Clark', '3rd Street', 345678))
 >>> f = open('phonebook','w')
 >>> pickle.dump(l, f)
 >>> f.close()

Loading:
 >>> import pickle
 >>> f2 = open('phonebook')
 >>> l = pickle.load(f2)
 >>> f2.close()
 >>> for item in l:
	print item

	
('Alan', '1st Street', 123456)
('Ben', '2nd Street', 234567)
('Clark', '3rd Street', 345678)

The file looks like this:
 >>> print open('phonebook').read()
(lp0
(S'Alan'
p1
S'1st Street'
p2
I123456
tp3
a(S'Ben'
p4
S'2nd Street'
p5
I234567
tp6
a(S'Clark'
p7
S'3rd Street'
p8
I345678
tp9
a.
 >>>

Ok, the file content might not seem completely obvious, but it's
not really so difficult to parse it, and it's certainly less verbose
than XML. Above all, much less code.

BTW, cPickle is faster than pickle, but I suspect it doesn't matter
with such a small amount of data. It's easy to replace "import pickle"
with "import cPickle as pickle" to try it out.



More information about the Python-list mailing list