如何在Python中刷新内部缓冲区?
内部缓冲区由你使用的运行时、库和编程语言创建,其目的是通过避免每次写入都进行系统调用来加快操作速度。相反,当写入文件对象时,你写入其缓冲区,当缓冲区满时,系统函数用于将数据写入实际文件。
语法
以下是flush()函数的语法:
File_name.flush()
它不接受任何参数。
此方法不返回任何内容;其返回类型为<class 'nonetype'="">。
示例-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():
广告