Binary file output using python

bvukov at teletrader.com bvukov at teletrader.com
Tue Apr 17 16:47:47 EDT 2007


On Apr 17, 10:30 pm, Thomas Dybdahl Ahle <lob... at gmail.com> wrote:
> Den Tue, 17 Apr 2007 11:07:38 -0700 skrev kyosohma:
>
> > On Apr 17, 12:41 pm, Chi Yin Cheung <c-che... at northwestern.edu> wrote:
> >> Hi,
> >> Is there a way in python to output binary files? I need to python to
> >> write out a stream of 5 million floating point numbers, separated by
> >> some separator, but it seems that all python supports natively is
> >> string information output, which is extremely space inefficient.
>
> I don't understand. To me it seams like there is no space difference:
>
> [thomas at localhost ~]$ python
> Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
> [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> f = open("test2", "w")
> >>> f.write(str(range(10**7)))
> >>> f.close()
> >>> f = open("test", "wb")
> >>> f.write(str(range(10**7)))
> >>> f.close()
>
> [thomas at localhost ~]$ ls -l test test2
> -rw-rw-r-- 1 thomas thomas 88888890 17 apr 22:28 test
> -rw-rw-r-- 1 thomas thomas 88888890 17 apr 22:27 test2
> [thomas at localhost ~]$

That's OK, but he might also take a look at the 'struct' module which
can solve the "stream of 5 million floating point numbers, separated
by
some separator" part of the issue ( if binary format is needed ). From
the python docs...
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8





More information about the Python-list mailing list