[Tutor] Structured files?

Steven D'Aprano steve at pearwood.info
Thu Jun 2 19:07:06 CEST 2011


Alan Gauld wrote:
> 
> "Alexandre Conrad" <alexandre.conrad at gmail.com> wrote
> 
>> you want to share that data between non-Python application, I could
>> also suggest the use of the JSON module. JSON is a standard format
>> (see json.org) supported by many programming languages. 
> 
> But isn't it a string based format?
> I thought JSON converted everything into XML strings?

JSON is a string format, but not XML.

 >>> import json
 >>> json.dumps({'a': 1, 'b': 2, 'c': 3})
'{"a": 1, "c": 3, "b": 2}'


YAML is another alternative, arguably more human readable than JSON, but 
it's not in the standard library.

Perhaps you're thinking of plist ("property list"). In Python 3.1:


 >>> from io import BytesIO
 >>> import plistlib
 >>> s = BytesIO()
 >>> plistlib.writePlist({'a': 1, 'b': 2, 'c': 3}, s)
 >>> print( s.getvalue().decode('ascii') )
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" 
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
         <key>a</key>
         <integer>1</integer>
         <key>b</key>
         <integer>2</integer>
         <key>c</key>
         <integer>3</integer>
</dict>
</plist>



> That makes it hugely wasteful of space which is usually the reason for 
> using a binary format in the first place.

Meh, who cares whether your 100K of data takes 300K on disk? :)

If you need/want binary storage, pickle has a binary mode. But 
generally, I am a big believer in sticking to text formats unless you 
absolutely have to use binary. The usefulness of being able to read, or 
even edit, your data files using a simple text editor cannot be 
under-estimated!


-- 
Steven



More information about the Tutor mailing list