Python File flush() 方法刷新内部缓冲区。维护此内部缓冲区以加快文件操作速度。
例如,每当对文件执行写入操作时,内容首先写入内部缓冲区;缓冲区满后,将其传输到目标文件中。这样做是为了防止每个写入操作的频繁系统调用。一旦文件关闭,Python 就会自动刷新缓冲区。但是您可能仍希望在关闭任何文件之前刷新数据。
该方法的工作方式类似于 stdio 的 fflush,并且可能对某些类似文件的对象无操作。
语法
以下是 Python 文件 flush() 方法的语法 -
fileObject.flush();
参数
该方法不接受任何参数。
返回值
此方法不返回任何值。
例以下示例显示了一个使用 Python File flush() 方法的简单程序。
# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
# Here it does nothing, but you can call it with read operation.
fo.flush()
# Close opened file
fo.close()
当我们运行上述程序时,它会产生以下结果——
Name of the file: foo.txt
例
当我们使用 flush() 方法时,它不会刷新原始文件,而只会刷新内部缓冲区内容。
在下面的示例中,我们在读取模式下打开一个文件,并读取文件内容。然后,使用 flush() 方法刷新内部缓冲区。打印文件中的内容以检查该方法是否修改了原始文件。
# Open a file
fo = open("hello.txt", "r")
print("Name of the file: ", fo.name)
file_contents = fo.read()
fo.flush()
print("Contents of the file: ", file_contents)
# Close opened file
fo.close()
在执行上述程序时,结果如下 -
Name of the file: hello.txt
Contents of the file: hello
Contents of the file: hello
例
即使未调用该方法,Python 也会在文件关闭后刷新内部缓冲区内容。
# Open a file
fo = open("test.txt", "w")
#Perform an operation on the file
print("Name of the file: ", fo.name)
# Close opened file
fo.close()
如果我们编译并运行上面的程序,输出显示如下 -
Name of the file: test.txt