Python 2.7:立即写入文件

elb*_*ajo 38 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 you look at outputFile.txt you will see 'First' and 'Second'"
Run Code Online (Sandbox Code Playgroud)

我怎么想让python立即写入输出文件?

RyP*_*eck 63

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

有关在open() 此处使用该参数的详细信息.

所以你会改变你的公开电话 -

outputFile = open("./outputFile.txt", "a", 0)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,第二个选项对我来说是最好的,因为我不想每次都写outputFile.flush()但两个都有效. (2认同)
  • @nachshon"完成同样的事情":在我的系统上不适合我(RHEL 6.8与[conda](https://en.wikipedia.org/wiki/Conda_(package_manager)) - 基于Python 2.7.13).在[ffeast](/sf/answers/2905471761/)中提到的`os.fsync()`调用是必需的(对于基于Microsoft Windows的Python或其他操作系统来说无法肯定). (2认同)

ism*_*ail 18

使用该flush()功能强制它,添加

outputFile.flush()
Run Code Online (Sandbox Code Playgroud)

在代码的最后.

  • 如果在Python文件的末尾添加了该代码,那么在文件关闭时无法完成任何操作.相反,它应该可能多次执行 - 每当需要确保到目前为止生成的所有输出都写入文件时. (4认同)

ffe*_*ast 7

正如@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库提供的用户空间缓冲区.为确保数据物理存储在磁盘上,必须刷新内核缓冲区,例如,使用sync(2)或fsync(2).


bgo*_*odr 7

只是将上述所有答案组合成一组有用的实用程序函数,因为OP(和我自己!)的一个关键要求是“因为我不想每次都编写 outputFile.flush() ”:

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 /sf/answers/2905471761/ 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")
Run Code Online (Sandbox Code Playgroud)