[Tutor] writing binary files

alan.gauld@bt.com alan.gauld@bt.com
Fri, 28 Jul 2000 12:45:17 +0100


> > 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.

Yes, I figured that bit.

> So you can use the struct module to convert Python data into binary
> strings, which can then be written to the file.

I knew there must be a way, but although Python has batteries 
included it can be hard to know which battery you need :-)

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

I don't think they'll help here, I'm trying to reproduce 
the proprietary format of an old legacy system to fix an 
operational proble, The format is well documented and I 
could just use emacs but I wanted to try Python as a more
future proof solution...

Thanks all for pointing out struct.

Alan G.