Python os.fsync() 方法



Python 的 fsync() 方法強制將給定檔案描述符的檔案寫入儲存磁碟。如果我們正在使用 Python 檔案物件(例如 f),則需要使用 f.flush() 方法清除內部緩衝區。然後,使用 os.fsync(f.fileno()) 來確保與檔案物件關聯的所有內部緩衝區都寫入磁碟。

通常,每當我們向檔案寫入資料時,在寫入磁碟之前,它都會儲存在緩衝區中。然後,作業系統決定何時將此緩衝區寫入磁碟。os.fsync() 方法用於在 "os.write()" 之後,以確保緩衝區中的所有資料都立即寫入磁碟。

語法

以下程式碼塊顯示了 fsync() 方法的語法:

os.fsync(fd)

引數

Python 的 os.fsync() 方法接受單個引數:

  • fd - 這是需要緩衝區同步的檔案描述符。

返回值

Python 的 os.fsync() 方法不返回值。

示例

在此示例中,我們以讀寫許可權開啟給定檔案的描述符。然後,我們將一個簡單的位元組字串寫入檔案,並使用 os.fsync() 方法確保它在關閉檔案描述符之前寫入磁碟。

#!/usr/bin/python
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, b"Welcome to Tutorialspoint")

# Now you can use fsync() method.
os.fsync(fd)

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("Read String is : ", str)

# Close opened file
os.close( fd )
print ("Closed the file successfully!!")

執行以上程式時,會產生以下結果:

Read String is :  b'Welcome to Tutorialspoint'
Closed the file successfully!!

示例

fsync() 方法可能會丟擲 IOError 和 OSError 等異常。以下示例演示瞭如何在 try-except-finally 塊中處理這些異常。

import os

# write operation in try block
try:
    # Open a file descriptor
    fd = os.open('foo.txt', os.O_RDWR|os.O_CREAT)

    # Write data to the file
    os.write(fd, b"This is Tutorialspoint")

    # Using os.fsync() method
    os.fsync(fd)

    # reading the file
    os.lseek(fd, 0, 0)
    str = os.read(fd, 100)
    print ("Read String is : ", str)
	
except Exception as exp:
    print(f"An error occurred: {exp}")
	
finally:
    # closing file
    os.close(fd)
    print("File closed successfully!!")

執行以上程式時,會產生以下結果:

Read String is :  b'This is Tutorialspoint'
File closed successfully!!
python_files_io.htm
廣告
© . All rights reserved.