[Tutor] writing binary files

Michael P. Reilly arcege@shore.net
Fri, 28 Jul 2000 07:39:45 -0400 (EDT)


> 
> How do I write binary data to a file?
> I can open a file with 'wb' as mode but if I do:
> 
> b = open('bin.dat','wb')
> for i in range(50): b.write(i)
> 
> I get an error.

This is an error because the write method can only output a string.
Strings in Python are not strictly 7-bit characters, but 8-bit bytes.
So you can use the struct module to convert Python data into binary
strings, which can then be written to the file.

>>> import struct
>>> binfile = open('bin.dat', 'wb')
>>> for num in range(50):
...   data = struct.pack('i', num)
...   binfile.write(data)
...
>>> binfile = open('bin.dat', 'rb')
>>> intsize = struct.calcsize('i')
>>> while 1:
>>>   data = binfile.read(intsize)
...   if data == '':
...     break
...   num = struct.unpack('i', data)
...   print num
...

Also, you might want to look at the marshal, pickle and shelve
modules.

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------