Python3 os.fsync()方法

fsync()方法强制将文件描述符fd写入到磁盘文件。如果已经从一个Python文件对象f 开始,那么先执行 fflush()然后执行 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!!

上一篇: Python3文件方法 下一篇: Python3 os文件目录的方法