Python os.fsync()方法

Python的os.fsync()方法返回強制將檔描述符fd寫入磁片。 如果使用Python檔對象f,首先要執行f.flush(),然後執行os.fsync(f.fileno()),以確保與f關聯的所有內部緩衝區都被寫入磁片。

語法

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

os.fsync(fd)

參數

  • fd − 這是緩衝區同步的檔描述符(必需的)。

返回值

  • 此方法沒有返回值。

示例

以下示例顯示了fsync()方法的用法。

#!/usr/bin/python3
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模組方法 下一篇: Python異常處理