Force Write File with File Descriptor to Disk in Python



You have to use the fdatasync(fd) function to force write of file with filedescriptor fd to disk. It does not force update of metadata. Also note that this is only available on Unix.

A more cross platform solution would be to use fsync(fd) as it force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function.

Example

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 )

Output

When we run above program, it produces following result:

Read String is :  This is test
Updated on: 2019-12-13T09:53:06+05:30

349 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements