如何在 Python 中刷新内部缓冲区?
programmingpythonserver side programming更新于 2025/3/22 16:12:17
内部缓冲区由您使用的运行时、库和编程语言创建,其目的是通过防止每次写入时都进行系统调用来加快操作速度。相反,在写入文件对象时,您会写入其缓冲区,当缓冲区已满时,将使用系统函数将数据写入实际文件。
语法
以下是 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():
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

