我意识到当我使用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立即写入输出文件?
答案 0 :(得分:61)
您可以使用flush()
,也可以将文件对象设置为无缓冲。
有关对open()
here使用该参数的详细信息。
因此,您可以将公开呼叫更改为 -
outputFile = open("./outputFile.txt", "a", 0)
答案 1 :(得分:16)
使用flush()
功能强制它,添加
outputFile.flush()
代码末尾。
答案 2 :(得分:6)
正如@RyPeck所说,您可以使用flush()
或设置文件对象
无缓冲。
但请注意以下内容(来自
https://docs.python.org/2/library/stdtypes.html?highlight=file%20flush#file.flush):
刷新内部缓冲区,如stdio的fflush()。
注意flush()不一定将文件的数据写入磁盘。使用flush()后跟os.fsync()来确保这种行为。
来自man 3 fflush
的引用:
请注意,fflush()仅刷新C库提供的用户空间缓冲区。为了确保数据物理存储在磁盘上,必须刷新内核缓冲区,例如, with sync(2)或fsync(2)。
答案 3 :(得分:3)
只是将上述所有答案合并到一组有用的实用程序函数中,因为OP(和我自己!)的关键要求是“because I don't want to write outputFile.flush() each time”:
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")