Python os.fdatasync() 方法



Python 的 os.fdatasync() 方法強制將指定檔案描述符的檔案寫入磁碟。與 os.fsync() 不同,後者也強制寫入磁碟,但包括元資料更新,而 fdatasync() 方法不強制元資料更新。

此方法用於防止在斷電或系統崩潰期間資料丟失。由於它僅對檔案的資料執行操作,因此它比 os.fsync() 方法更快。

語法

以下是 fdatasync() 方法的語法:

os.fdatasync(fd);

引數

Python 的 os.fdatasync() 方法接受一個引數:

  • fd − 這是要寫入資料的檔案描述符。

返回值

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

示例

以下示例顯示了 fdatasync() 方法的基本用法。在這裡,我們正在寫入檔案並將其同步以將其狀態與儲存裝置儲存。

#!/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"This is tutorialspoint")
# Now you can use fdatasync() method.
os.fdatasync(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'This is tutorialspoint'
Closed the file successfully!!

示例

為了處理同步期間任何潛在的錯誤或異常,我們可以使用 try-accept-finally 塊,如下例所示。

import os

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

try:
   # Writing to the file
   dataStr = b"Welcome to Tutorialspoint"
   os.write(fd, dataStr)

   # Synchronizing the data to disk
   os.fdatasync(fd)
   print("Data synced successfully!!")

except OSError as exp:
   print(f"An error occurred: {exp}")

finally:
   # Close the file descriptor
   os.close(fd)
   print("File closed successfully!!")

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

Data synced successfully!!
File closed successfully!!
python_files_io.htm
廣告