如何使用Python强制将具有filedescriptor 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