Python os.fsync() Method
os.fsync() Overview
The os.fsync() method forces a file with the file descriptor fd to be written to the hard disk. On Unix, the fsync() function will be called; on Windows, the _commit() function will be called.
If you are about to manipulate a Python file object f, first f.flush(), then os.fsync(f.fileno()), making sure that all memory associated with f is written to the hard disk. Valid on unix, Windows.
Available on Unix, Windows.
os.fsync() Syntax
The fsync() method syntax format is as follows:
os.fsync(fd)
os.fsync() Parameters
- fd – Descriptor of the file.
os.fsync() Return Value
This method has no return value.
os.fsync() Demo#1
The following example demonstrates the use of the fsync() method.
#!/usr/bin/python3
import os, sys
# Open file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Writing strings
os.write(fd, "This is test")
# Use the fsync() method.
os.fsync(fd)
# Read Content
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("The read string is :", str)
# Close file
os.close( fd)
print ("Close file successfully!!!")
Output:
The read string is :This is test
Close file successfully!!!
os.fsync() Demo#2
Use of os.fsync() method.
# Python program to explain os.fsync() method in apidemos.com
# 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
os.fsync() Demo#3
If working with file objects
# Python program to explain os.fsync() method in apidemos.com
# 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