如何在 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():

更新於:2022年8月18日

2K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.