multiple file objects for some file?

Jeff Epler jepler at unpythonic.net
Sun Jul 27 21:59:33 EDT 2003


On Sun, Jul 27, 2003 at 01:17:50PM -0400, Tim Peters wrote:
> You can get in deep trouble if the file mutates, though.  Python's file
> objects are wrappers around C's streams, and each C stream has its own
> buffers.  So, for example, a mutation (a file write) made via one file
> object won't necessarily update the buffers held by the other file objects
> (it depends on how your platform C works, but I don't know of any that
> automagically try to update buffers across multiple streams open on the same
> file), and then reading via some other file object may continue to see stale
> data (left over in its buffer).

... I believe you're "safe" if you always:
1) flush() after a write that may be followed by a read:
	f.write("abcd"); f.flush()
2) perform a no-op seek() before a read that may follow a write
	SEEK_CUR=1
	f1.seek(0, SEEK_CUR); f.read(4)

Furthermore, using a "0" buffering argument to open() [in the reader
and the writer] should save you from needing to do this, *but* it may
negatively impact performance.

Finally, you could use os.open/os.read/os.write, which should not have
these buffering problems, but will also not have the performance gain of
stdio buffering.  This performance diference may or may not be
significant in your application.

Jeff





More information about the Python-list mailing list