Python 檔案 flush() 方法



Python 檔案flush() 方法會重新整理內部緩衝區。此內部緩衝區用於加快檔案操作速度。

例如,每當對檔案執行寫入操作時,內容首先寫入內部緩衝區;當緩衝區滿時,再將緩衝區中的內容傳輸到目標檔案。這樣做是為了避免每次寫入操作都頻繁呼叫系統呼叫。檔案關閉後,Python 會自動重新整理緩衝區。但是,您可能仍然希望在關閉任何檔案之前重新整理資料。

此方法的工作方式類似於 stdio 的 fflush,並且在某些類檔案物件上可能什麼也不做。

語法

以下是 Python 檔案flush() 方法的語法:

fileObject.flush(); 

引數

此方法不接受任何引數。

返回值

此方法不返回值。

示例

以下示例演示了一個使用 Python 檔案 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

示例

即使不呼叫該方法,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
python_file_methods.htm
廣告