Python 2.7 : Write to file instantly

后端 未结 4 1542
粉色の甜心
粉色の甜心 2020-11-27 05:03

I realized that when I write into a file using python it wait until the end of my Python file to execute it:

outputFile = open(\"./outputFile.txt\",\"a\")
ou         


        
4条回答
  •  失恋的感觉
    2020-11-27 05:20

    As @RyPeck said you can use flush() or set the file object to be unbuffered. But note the following (from https://docs.python.org/2/library/stdtypes.html?highlight=file%20flush#file.flush):

    Flush the internal buffer, like stdio‘s fflush().

    Note flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.

    And a quote from man 3 fflush:

    Note that fflush() only flushes the user-space buffers provided by the C library. To ensure that the data is physically stored on disk the kernel buffers must be flushed too, for example, with sync(2) or fsync(2).

提交回复
热议问题