os.fsync() 方法



描述

fsync() 方法強制將檔案描述符 fd 對應的檔案寫入磁碟。如果從 Python 檔案物件 f 開始,首先執行 f.flush(),然後執行 os.fsync(f.fileno()),以確保與 f 相關的所有內部緩衝區都寫入磁碟。

語法

以下是 fsync() 方法的語法:-

os.fsync(fd)

引數

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

返回值

此方法不返回值。

示例

以下示例顯示了 fsync() 方法的使用:-

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

# Write one string
line="this is test"
b=line.encode()
os.write(fd, b)

# Now you can use fsync() method.
# Infact here you would not be able to see its effect.
os.fsync(fd)

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

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

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

Read String is : this is test
Closed the file successfully!!
python_os_file_directory_methods.htm
廣告