Python 2.7:立即写入文件

Python 2.7:立即写入文件,python,python-2.7,Python,Python 2.7,我意识到,当我使用python写入一个文件时,它会等到python文件结束时才执行它: outputFile = open("./outputFile.txt","a") outputFile.write("First") print "Now you have 10sec to see that outputFile.txt is still the same as before" time.sleep(10) outputFile.write("Second") print "Now if

我意识到,当我使用python写入一个文件时,它会等到python文件结束时才执行它:

outputFile = open("./outputFile.txt","a")
outputFile.write("First")
print "Now you have 10sec to see that outputFile.txt is still the same as before"
time.sleep(10)
outputFile.write("Second")
print "Now if you look at outputFile.txt you will see 'First' and 'Second'"

如何让python立即写入输出文件?

使用
flush()
函数强制写入,添加

outputFile.flush()
在代码末尾。

您可以使用
flush()
或将文件对象设置为无缓冲

有关将该参数用于
open()
的详细信息

所以你会把你的公开电话改成-

outputFile = open("./outputFile.txt", "a", 0)

正如@RyPeck所说,您可以使用
flush()
或将file对象设置为 无缓冲。 但请注意以下内容(来自 ):

刷新内部缓冲区,如stdio的fflush()

注意:flush()不一定将文件的数据写入磁盘。使用flush()后跟os.fsync()以确保此行为

还有一段引自
man3fflush

注意,fflush()只刷新C库提供的用户空间缓冲区。为了确保数据物理存储在磁盘上,内核缓冲区也必须刷新,例如, 使用同步(2)或fsync(2)


只需将上述所有答案组合成一组有用的实用函数,因为(和我自己!)的一个关键要求是“”:


如果将该代码添加到Python文件的末尾,那么在关闭文件时不会完成任何事情。相反,它应该被执行多次——只要需要确保到目前为止生成的所有输出都写入到文件中每次都可以,但两者都可以。与其在时间密集型操作期间让文件保持打开状态,不如考虑with语句来完成相同的事情。@nachshon“完成相同的事情”:在我的系统上不适合我(RHEL 6.8和基于Python的2.7.13)。在的回答中提到的
os.fsync()
调用是必需的(不能肯定是否适用于基于Microsoft Windows的Python或其他操作系统)。@Nam
os.fsync()
在我的系统上工作得非常好(RHEL 6.8和基于Python的2.7.13)。你确定没有文件系统问题或系统过载吗?我不知道。我在Ubuntu桌面16和Python 2.7上
import os
import tempfile
import time


def write_now(filep, msg):
    """Write msg to the file given by filep, forcing the msg to be written to the filesystem immediately (now).

    Without this, if you write to files, and then execute programs
    that should read them, the files will not show up in the program
    on disk.
    """
    filep.write(msg)
    filep.flush()
    # The above call to flush is not enough to write it to disk *now*;
    # according to https://stackoverflow.com/a/41506739/257924 we must
    # also call fsync:
    os.fsync(filep)


def print_now(filep, msg):
    """Call write_now with msg plus a newline."""
    write_now(filep, msg + '\n')


# Example use with the with..as statement:
with tempfile.NamedTemporaryFile(prefix='some_prefix_here.', suffix='.log', dir='.', delete=False) as logf:
    print_now(logf, "this is a test1")
    time.sleep(20)
    print_now(logf, "this is a test2")