Python os.fdatasync() Method



The Python os.fdatasync() method forces write of file with the specified filedescriptor to disk. Unlike the os.fsync(), which also forces a write to disk but includes metadata updates, the fdatasync() method does not force the metadata update.

This method is used to prevent data loss during a power failure or system crash. Since it performs operation only on file's data, it is faster than os.fsync() method.

Syntax

Following is the syntax for fdatasync() method −

os.fdatasync(fd);

Parameters

The Python os.fdatasync() methods accepts a single parameter −

  • fd − This is the file descriptor for which data to be written.

Return Value

The Python os.fdatasync() method does not return any value.

Example

The following example shows the basic use of fdatasync() method. Here, we are writing into a file and synchronizing it to save its state with storage device.

#!/usr/bin/python
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string
os.write(fd, b"This is tutorialspoint")
# Now you can use fdatasync() method.
os.fdatasync(fd)
# Now read this file from the beginning.
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print("Read String is : ", str)
# Close opened file
os.close( fd )
print("Closed the file successfully!!")

When we run above program, it produces following result −

Read String is :  b'This is tutorialspoint'
Closed the file successfully!!

Example

To handle any potential error or exception during the synchronization, we can use the try-accept-finally block as shown in the below example.

import os

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

try:
   # Writing to the file
   dataStr = b"Welcome to Tutorialspoint"
   os.write(fd, dataStr)

   # Synchronizing the data to disk
   os.fdatasync(fd)
   print("Data synced successfully!!")

except OSError as exp:
   print(f"An error occurred: {exp}")

finally:
   # Close the file descriptor
   os.close(fd)
   print("File closed successfully!!")

On running, the above program produces following result −

Data synced successfully!!
File closed successfully!!
python_files_io.htm
Advertisements