Using struct writing integers

Gordon McMillan gmcm at hypernet.com
Thu Apr 27 14:22:01 EDT 2000


thomas at cintra.no wrote:

> Hi,
> 
> I got a list of tuples containing integers, like :
> 
> stuff = [ (21,323,32), (432,43,3234), (432,565,532), (434,43,987)
> ]
> 
> Each tuple in the list represent an id for a entry in a database,
> the three integers form a key. The list above contains four ids.
> I want to write them to a binary file using the struct module.
> Then I want to read them pack, unpack them into the same kind of
> list.
> 
> Any hints, examples etc?

>>> stuff = [ (21,323,32), (432,43,3234), (432,565,532), 
(434,43,987) ]
>>> import struct
>>> f = open('test.out','wb')
>>> fmt = 'lll'
>>> sz = struct.calcsize(fmt)
>>> for x,y,z in stuff:
...   f.write(struct.pack(fmt, x, y, z))
...
>>> f.close()
>>> stuff2 = []
>>> f = open('test.out', 'rb')
>>> while 1:
...  s = f.read(sz)
...  if not s:
...    break
...  tpl = struct.unpack(fmt, s)
...  stuff2.append(tpl)
...
>>> stuff2
[(21, 323, 32), (432, 43, 3234), (432, 565, 532), (434, 43, 987)]

- Gordon




More information about the Python-list mailing list