faqts : Computers : Programming : Languages : Python : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

47 of 62 people (76%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How do I create a binary file and write to it?

May 25th, 2000 07:26
unknown unknown, Travis Oliphant


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