Python 如何刷新内部缓冲区
内部缓冲区的目的是通过阻止每次写操作都进行系统调用来加快操作速度。相反,当写入文件对象时,您将写入其缓冲区,当缓冲区已满时,系统功能将用于将数据写入实际文件。
语法
flush()函数的语法如下:
File_name.flush()
它不接受任何参数。
该方法没有返回值;它的返回类型是
示例1
下面的程序中的 flush() 方法只是清除了文件的内部缓冲区;文件的实际内容没有受到影响。因此,可以读取和查看文件中的内容−
# Create a file
file = open("flush.txt", "w")
# Write the text in the file
file.write("Tutorials Point")
# Flush the internal buffer
file.flush()
# Close the file
file.close()
# Read and write the content present in the file
file = open("flush.txt", "r+")
print("The content in the file is file.flush()")
print(file.read())
file.close()
输出
以下是上述代码的输出 −
The content in the file is file.flush()
Tutorials Point
示例2
在下面的程序中,我们创建了一个文本文件,并写入其中一些内容,然后关闭了文件。在读取和显示文件内容之后,执行了flush()函数,清除文件的输入缓冲区,使得文件对象不再读取任何内容,文件内容变量保持为空。结果是,在flush()过程之后没有显示任何内容。
# Create a file
file = open("flush.txt", "w+")
# Write in the file
file.write("Tutorials Point file.flush() is performed. The content isn't flushed")
# Close the file
file.close()
# Open the file to read the content present in it
file = open("flush.txt", "r")
# Read the content present in the before flush() is performed
Content = file.read()
# dDisplay the contents
print("\nBefore performing flush():\n", Content)
# Clear the input buffer
file.flush()
# Read the content after flush() function is performed but reads nothing since the internal buffer is already cleared
Content = file.read()
# Display the contents now
print("\nAfter performing the flush():\n", Content)
# Close the file
file.close()
输出
以下是以上代码的输出 –
Before performing flush():
Tutorials Point file.flush() is performed. The content isn't flushed
After performing the flush():
极客笔记