Can I save a text file in python without closing it?

前端 未结 3 1747
-上瘾入骨i
-上瘾入骨i 2021-01-05 07:23

I am writing a program in which I would like to be able to view a log file before the program is complete. I have noticed that, in python (2.7 and 3), that file.write(

相关标签:
3条回答
  • 2021-01-05 08:02

    You would need this:

    file.flush()
    # typically the above line would do. however this is used to ensure that the file is written
    os.fsync(file.fileno())
    

    Check this: http://docs.python.org/2/library/stdtypes.html#file.flush

    file.flush() Flush the internal buffer, like stdio‘s fflush(). This may be a no-op on some file-like objects. Note flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.

    EDITED: See this question for detailed explanations: what exactly the python's file.flush() is doing?

    0 讨论(0)
  • 2021-01-05 08:12

    This will write the file to disk immediately:

    file.flush()
    os.fsync(file.fileno())
    

    According to the documentation https://docs.python.org/2/library/os.html#os.fsync

    Force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function.

    If you’re starting with a Python file object f, first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.

    0 讨论(0)
  • 2021-01-05 08:17

    Does file.flush() after each write help?

    Hannu

    0 讨论(0)
提交回复
热议问题