如何使用 Python 強制將檔案透過檔案描述符 fd 寫入磁碟?


您必須使用 fdatasync(fd) 函式來強制將檔案透過檔案描述符 fd 寫入磁碟。它不會強制更新元資料。另外注意這僅適用於 Unix。

一種更跨平臺的解決方案是使用 fsync(fd) 函式,因為它強制將被檔案描述符 fd 寫入磁碟。在 Unix 上,它呼叫本機 fsync() 函式;在 Windows 上,呼叫 MS _commit() 函式。

示例

import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
os.write(fd, "This is test")
# 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
os.close( fd )

輸出

當我們執行上述程式時,它產生以下結果

Read String is :  This is test

更新時間:13-12-2019

301 瀏覽量

開啟 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.