On Wed, 12 Jan 2005, Marilyn Davis wrote:

> I was looking at my use of file objects and file descriptors and I wrote
> this sample program and was very surprised by the result -- which makes
> me think there's something here that I don't understand. Where did my
> 'ooo' go?
>
> #! /usr/bin/env python
> import os
>
> fobj = open('/tmp/xxx','w')
> fobj.write('ooo\n')
> fp = fobj.fileno()
> os.write(fp,'x\n')
> os.close(fp)


Hi Marilyn,

Oh!  Can you explain why you're mixing the low-level 'os.write()' and
'os.close()' stuff with the high-level file methods?

The 'os' functions work at a different level of abstraction than the file
object methods, so there's no guarantee that:

    os.close(fp)

will do the proper flushing of the file object's internal character
buffers.


Try this instead:

###
fobj = open('/tmp/xxx','w')
fobj.write('ooo\n')
fobj.write('x\n')
fobj.close()
###


The documentation on os.write() says:

"""Note: This function is intended for low-level I/O and must be applied
to a file descriptor as returned by open() or pipe(). To write a ``file
object'' returned by the built-in function open() or by popen() or
fdopen(), or sys.stdout or sys.stderr, use its write() method."""

    (http://www.python.org/doc/lib/os-fd-ops.html#l2h-1555)

I think the documentation is trying to say: "don't mix high-level and
low-level IO".


For most purposes, we can usually avoid using the low-level IO functions
os.open() and os.write().  If we're using the low-level file functions
because of pipes, then we can actually turn pipes into file-like objects
by using os.fdopen().  os.fdopen() is a bridge that transforms file
descriptors into file-like objects.  See:

    http://www.python.org/doc/lib/os-newstreams.html

for more information on os.fdopen().



I hope this helps!

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to