Creating binary files
Travis Oliphant
olipt at mayo.edu
Wed May 24 10:10:31 EDT 2000
> Hello!
>
> I'm feeling more than a bit stupid for asking this but I'm stumped.
>
> How do I create a binary file and write to it?
>
> I need to create an binary file to store a large number of integers in
> The file HAS to be binary since it's going to be read by an another
> program which isn't in Python.
>
> I know how to open a binary file
>
> bfile = open("bfile","wb")
>
> but how do I write an integer into the file?
>
> n = 1066
> b.write(n) # this will not work!
> b.write(repr(n)) # will not write binary
>
>
> // Anders
>
The idea is to write a string to the file where the string is just a
collection of bytes representing the data. There are lot's of ways to
proceed here.
(1) Use the struct module to create a string with the machine
representation of the integer in question and write that out:
import struct
n = 1066
bfile.write(struct.pack('i',n))
(2) Use the *default* array module to store the numbers and then use it's
tofile() method or its tostring() method
import array
numbers = array.array('i',[1066,1035,1032,1023])
bfile.write(numbers.tostring())
## OR
numbers.tofile(bfile)
(3) Use Numerical Python's array module to store the numbers and then
use the tostring() method of the NumPy array.
import Numeric
numbers = Numeric.array([1,2,3,4,5,6],'i')
bfile.write(numbers.tostring())
(4) Use Numerical Python and mIO.py which is part of signaltools
(http://oliphant.netpedia.net). This will let you write a binary file
directly from a NumPy array (without the intervening copy-to-string which
can save a lot of memory if you have *a lot* of numbers).
import mIO, Numeric
bfile = mIO.fopen('somefile','w')
numbers = Numeric.array([1,2,3,4,5,6],'i')
bfile.fwrite(numbers)
bfile.close()
# You could also say for example
# bfile.fwrite(numbers,'float') to write them as floats
More information about the Python-list
mailing list