AW: Write to a binary file

Grant Edwards grante at visi.com
Thu Apr 5 10:38:06 EDT 2007


On 2007-04-05, Thomi Aurel RUAG A <Aurel.Thomi at ruag.com> wrote:

> A simplified test programm to compare the function for opening
> a file i used ("file()") and your suggested "os.open()" showed
> different behaviour.
>
> My simple testprogramm:
>
> --- START ---
> import os
>
> msg = chr(0x02) + chr(0x36) + chr(0x00) + chr(0x01) + chr(0x0a) +
> chr(0xb0) + chr(0x77)
>
> f = os.open('/dev/pytest', os.O_RDWR)
> os.write(f,msg)
> os.close(f)
>
> f = file('/dev/pytest', 'wb')
> f.write(msg)
> f.close()
> --- END ---
>
> The "pytest" device is a very simple device-driver which
> prints out (using "printk()") the buffer delivered to the
> write function in a hexadecimal format ("Pytest write> [buffer
> in hex format]").
>
> The output was:
> --- Start ---
> Pytest write> 02 36 00 01 0a b0 77
> Pytest write> 02 36 00 01 0a
> Pytest write> b0 77
> --- END ---

I'm surprised that the normal file object's write method does
that -- especially for a "binary" file.  IMO, it's a bug when a
binary file object treats 0x0a differently than other byte
values.  But, using the file object to read/write a device is
probably not a good idea because of undefined behavior like
that.  File objects also do their own buffering, which I
suspect isn't what you want.

> Using os.open will work for me, i wasn't aware of the
> existence of several file interaces.

The os.file/open ones are just very thin wrappers around the
corresponding libc routines.  The file object contains it's own
buffering and other features that will just get in the way of
what you probably want to do.

-- 
Grant Edwards                   grante             Yow!  .. here I am in 53
                                  at               B.C. and all I want is a
                               visi.com            dill pickle!!



More information about the Python-list mailing list