如何使用 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.