Python | os.fdatasync 函數

最近更新時間 2020-12-08 12:28:37

os.fdatasync 函數強制將文件描述符 fd 指定文件寫入磁盤。不強制更新元數據。與 os.fsync() 方法不同,它不會強制更新元數據。

該功能在 MacOS 中不可用。

os.fdatasync() 方法比os.fsync() 方法更快,因為它只需要強制一次寫入磁盤而不是兩次。

文件描述符是一個數字,用於唯一標識計算機操作系統中打開的文件。它描述了數據資源,以及如何訪問該資源。

在類Unix操作系統上,默認情況下,前三個文件描述符為STDIN(標準輸入 0),STDOUT(標準輸出 1)和STDERR(標準錯誤 2)。

可以用 io.fileno() 可以獲得 file object 所對應的文件描述符。需要注意的是,直接使用文件描述符會繞過文件對象的方法,會忽略如數據內部緩衝等情況。

函數定義

os.fdatasync(fd)
# 函數定義

if sys.platform != 'win32':
    # Unix only
    ...
    def fdatasync(fd: int) -> None: ...  # Unix only, not Mac
    ...

兼容性:Unix 系統。

參數

  • checkfd - 源文件描述符。

返回值

  • checkNone - 無。

示例1: - 使用 os.fdatasync() 函數強制將指定文件寫入磁盤。

# coding=utf-8

# Python3 代碼
# 講解怎樣使用 os.fdatasync() 函數強制將指定文件寫入磁盤

# 引入 os 庫
import os

# 文件路徑
path = "foo.txt"

# 根據路徑打開文件
fd = os.open(path, os.O_WRONLY)

# 寫入 byte 字符串
os.write(fd, b"foofoofoo")

# 寫入的內容可能在緩存中沒有寫入到磁盤
# 程序結束或者文件描述符關閉時才會寫入
# 可以使用 os.fdatasync() 強制寫入
os.fdatasync(fd)
print("Force write of file committed successfully") 

# Close the file descriptor  
os.close(fd)
Force write of file committed successfully
rss_feed