[Tutor] Writing BINARY-CONTENT

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Nov 24 17:30:25 EST 2003

On Mon, 24 Nov 2003, Stefan Dieck wrote:

> >> a = open('c:\\test.me', 'wb')   # opens a file for binary writing
> >This is correct for writing binary.  Are you sure that the program or
> > editor you're using to check this isn't opening the file in text mode
> > (with 'r' instead of 'rb')?
> Yes I'm sure to open in binary mode
> There is a huge problem around this:
>  If I want write 256 "different" bytes. Python put 257 bytes to the
> File.  On reading, the lenght is 256 bytes to work with. (-1)

Hi Stefan,

Hmmm... that sounds strange!  Let's test this.

>>> f = open("test_binary.bin", "wb")
>>> for i in range(256):
...     f.write(chr(i))
>>> f.close()
>>> f = open('test_binary.bin', 'rb')
>>> data = f.read()
>>> len(data)

> It seems like the size I expect, but the file on the disk has more
> bytes. (not really good for binaries)

>>> import os
>>> os.system('ls -l test_binary.bin')
-rw-r--r--    1 dyoo     users         256 Nov 24 14:22 test_binary.bin

On my end, this appears to work consistantly.

>  But such a behavior can corrupt my data.

Sure.  But let's take another glance at the program that's doing the
writing, just to make sure we're not missing something silly.  *grin*

Can you show us what program you used to write those bytes to disk?
Perhaps a stray byte is getting passed into write()?  Also, show us also
how you're measuring the file size afterwards.  With that information, One
of us can then try to duplicate the problem on our end.

Good luck to you!

More information about the Tutor mailing list