fo.flush() & fo.write() on windows

Tim Peters tim_one at email.msn.com
Sun Aug 29 20:41:07 EDT 1999


[Roberts, Robert J]
> Am I asking too much?

On Windows, yes.  C's stdio isn't its native file-handling system, and its
implementation of stdio is, umm, "surprising".

> pseudo code:

>     fo = __builtin__.open(foName, 'a')

Why not plain "open"?

>     foSize = os.stat(foName)[6]     # if foSize = 100...

os.path.getsize(foName) is easier on the brain (new in 1.5.2 though).

>     fo.write('Some string.')             # fo.write() returns None

file.write() always returns None, as documented.  Don't know what you expected
it to return, but read the docs.

>     foSize = os.stat(foName)[6]    # ...foSize STILL = 100.

Unsurprising so far.

>     fo.flush()
>     foSize = os.stat(foName)[6]    # ...foSize STILL = 100.

Ah -- *that's* Windows <wink>!

>     fo.close()                     # 'Some string' appears in fo.
>     foSize = os.stat(foName)[6]    # [now the bytes appear]
>
> I am running Python 1.5.2 on Windows 95. fo.write() appears to be
> buffering the write and returning None for bytes written on
> fo.write().

"None" is expected (see above).  Buffering should be expected too since you
opened the file with buffering.  If you don't want buffering, pass 0 as the
third arg:

     fo = open(foName, 'a', 0)

Alas, on Windows that won't make much of a difference in what you see.

> fo.flush() appears to do nothing.

MS's implementation of stdio's fflush (which Python's file.flush() calls
directly) does clear the stdio buffers, but merely flushes them to Windows'
internal buffers.  It does not imply commitment to disk.  The only way to get
that under Windows is to pass the non-standard "c" (for Commit) mode flag to
"open":

    fo = open(foName, 'ac')

Then fo.write(whatever) *still* won't (necessarily) show up on disk right away,
but fo.flush() will work the way you expect.  "c" is unportable, and much as
you may think you want it now <wink>, slows down Windows output enormously.

windows-was-designed-under-the-assumption-that-it-would-
    never-crash<snort>-ly y'rs  - tim






More information about the Python-list mailing list