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

前端 未结 3 1764
-上瘾入骨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: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.

提交回复
热议问题