Open In App

Python | os.fsync() method

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.fsync() method in Python is used to force write of the file associated with the given file descriptor. 
In case, we are working with a file object( say f) rather than a file descriptor, then we need to use f.flush() and then os.fsync(f.fileno()) to ensure that all buffers associated with the file object f 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: Use of os.fsync() method 
 




# Python program to explain os.fsync() method
   
# importing os module
import os
 
 
# File path
path = 'file.txt'
 
# Open the file and get
# the file descriptor
# associated with
# using os.open() method
fd = os.open(path, os.O_RDWR)
 
 
# Write a bytestring
str = b"GeeksforGeeks"
 
os.write(fd, str)
 
 
# The written string is
# available in program buffer
# but it might not actually
# written to disk until
# program is closed or
# file descriptor is closed.
 
# sync. all internal buffers
# associated with the file descriptor
# with disk (force write of file)
# using os.fsync() method
os.fsync(fd)
print("Force write of file committed successfully")
 
# Close the file descriptor
os.close(fd)

Output: 

Force write of file committed successfully

 

Code #2: If working with file objects 
 




# Python program to explain os.fsync() method
   
# importing os module
import os
 
 
# File path
path = 'file.txt'
 
# Open the file and get
# the file object
# using open() method
f = open(path, 'w')
 
 
# Write a string to
# the file object
str = "GeeksforGeeks"
f.write(str)
 
 
# Firstly, flush internal buffers
f.flush()
 
# Now, sync. all internal buffers
# associated with the file object
# with disk (force write of file)
# using os.fsync() method
os.fsync(f.fileno())
 
print("Force write of file committed successfully")
 
# Close the file object
f.close()

Output: 
Force write of file committed successfully

 


Article Tags :