writing to a binary file without intervening spaces
castironpi at gmail.com
castironpi at gmail.com
Mon Mar 17 08:15:28 EDT 2008
On Mar 17, 3:28 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Larry <larry.cebu... at gmail.com> writes:
> > My data is a = [23, 45, 56, 255].
> > My desire output is: 234556255, of course in binary file
> > representation already.
>
> > I tried to make one using write after pack method of struct module,
> > but because of spaces I got incorrect results.
>
> struct.pack works for me:
>
> Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
> >>> import struct, os
> >>> x = struct.pack('BBBB', 23, 45, 56, 255)
> >>> len(x)
> 4
> >>> f = open('/tmp/foo','w'); f.write(x); f.close()
> >>> os.system("ls -l /tmp/foo")
> -rw------- 1 phr phr 4 Mar 17 01:27 /tmp/foo
> >>>
>
> You could also do the list-string conversion with the array module.
Python 3.0a2 (r30a2:59405M, Dec 7 2007, 15:23:28) [MSC v.1500 32 bit
(Intel)] o
n win32
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes( [ 23, 45, 56, 255 ] )
b'\x17-8\xff'
>>> a= _
>>> f= open('temp.x','wb')
>>> f.write( a )
4
>>> f= open('temp.x','rb')
>>> f.read()
b'\x17-8\xff'
More information about the Python-list
mailing list