Reading and writing binary data to/from file objects
Hi,
I want to read binary data from a file using fromfile. This works as
long as I use a file name as argument to fromfile. With a file object
the data is wrong!
Consider the following example:
from numpy import *
fname='file.bin'
fname2='file2.bin'
a = arange(1, 30)
print type(a[0])
print "\noriginal data"
print a
# write to file name
a.tofile(fname)
# write to file object
f = open(fname2, 'w')
a.tofile(f)
f.close()
print "\nWritten to file name, read from file name"
b = fromfile(fname, dtype=int32)
print b
print "\nWritten to file name, read from file object"
f = open(fname, 'r')
b = fromfile(f, dtype=int32)
f.close()
print b
print "\nWritten to file object, read from file name"
b = fromfile(fname2, dtype=int32)
print b
print "\nWritten to file object, read from file object"
f = open(fname2, 'r')
b = fromfile(f, dtype=int32)
f.close()
print b
This prints:
ke, 2010-05-26 kello 14:07 +0200, Christoph Bersch kirjoitti:
f = open(fname2, 'w') [clip] Am I doing something substantially wrong or is this a bug?
You are opening files in text mode. Use mode 'wb' instead. -- Pauli Virtanen
Pauli Virtanen schrieb:
ke, 2010-05-26 kello 14:07 +0200, Christoph Bersch kirjoitti:
f = open(fname2, 'w') [clip] Am I doing something substantially wrong or is this a bug?
You are opening files in text mode. Use mode 'wb' instead.
That was it, thank you! Linux does not seem to care about binary or text mode. As I develop under Linux I was a bit puzzled by the different behaviour on Windows. Christoph
participants (2)
-
Christoph Bersch
-
Pauli Virtanen