Python | os.fsync () method

Python Methods and Functions

os.fsync() is used in Python to force the file associated with a given file descriptor to be written.

In case we are working with a file object (say f) and not a file descriptor, then we need to use f.flush () and then os.fsync (f.fileno ()), to ensure that all buffers associated with the F file object are written to disk.

Syntax: os.fsync (fd)

Parameter:
fd: A file descriptor for which buffer sync is required.

Return type: This method does not return any value.

Code # 1: Using the method os.fsync ()

Exit :

 Force write of file committed successfully 

Code # 2: When working with file objects

# Python program to explain the os.fsync () method

  # import of the os module

import os

 

 
# File path

path = ' file.txt'

 
# Open the file and get
# file descriptor
# associated with
# using the os.open () method

fd = os. open (path, os.O_RDWR)

 

 
# Write a byte line

str = b "GeeksforGeeks"  

 

os.write (fd, str )

 

 
# Written string
# available in the program buffer
# but it really isn't
# written to disk before
# the program is closed or
# the file descriptor is closed.

 
# sync all internal buffers
# associated with file descriptor
# with disk (will force a separate file entry)
# using the os.fsync () method
os.fsync (fd)

print ( "Force write of file committed successfully " )

  
# Close the file descriptor
os.close (fd)

# Python program to explain the os.fsync () method

  
# import of the os module

import os

 

  
# File path

path = 'file.txt'

  
# Open the file and get
# the file object
# using the open () method

f = open (path, 'w' )

 

 
# Write a line in
# file object

str = "GeeksforGee ks " 

f.write ( str )

 

 
# Flush internal buffers first
f.flush ()

 
# Now sync. all internal buffers
# associated with the file object
# with disk (force the file to be written)
# using the os.fsync () method
os.fsync (f.fileno ())

 

print ( "Force write of file commited successfully" )

  
# Close object file
f.close ()

Exit :

 Force write of file committed successfully