Python os.fsync() Method



The Python fsync() method forces write of a file with a given file descriptor to the storage disk. If we are working with a Python file object (say f) it is necessary to use f.flush() method so that internal buffer gets cleared. Then, use os.fsync(f.fileno()) to ensure that all internal buffers associated with file object are written to disk.

Generally, whenever we write data to a file, before getting written to disk, it is stored in a buffer. Then, the operating system decides when to write this buffer to disk. The os.fsync() method is used after "os.write()" to ensure that all data in the buffer should written to disk immediately.

Syntax

The following code block shows the syntax of fsync() method −

os.fsync(fd)

Parameters

The Python os.fsync() method accepts a single parameter −

  • fd − This is the file descriptor for buffer sync is required.

Return Value

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

Example

In this example, we open a file descriptor for the given file with read and write permissions. We then write a simple byte string to the file and use os.fsync() method to ensure it's written to the disk before closing the file descriptor.

#!/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"Welcome to Tutorialspoint")

# 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)

# Close opened file
os.close( fd )
print ("Closed the file successfully!!")

When we run above program, it produces following result −

Read String is :  b'Welcome to Tutorialspoint'
Closed the file successfully!!

Example

The fsync() method can throw exceptions like IOError and OSError. The following example shows how to handle these exceptions in try-except-finally block.

import os

# write operation in try block
try:
    # Open a file descriptor
    fd = os.open('foo.txt', os.O_RDWR|os.O_CREAT)

    # Write data to the file
    os.write(fd, b"This is Tutorialspoint")

    # Using os.fsync() method
    os.fsync(fd)

    # reading the file
    os.lseek(fd, 0, 0)
    str = os.read(fd, 100)
    print ("Read String is : ", str)
	
except Exception as exp:
    print(f"An error occurred: {exp}")
	
finally:
    # closing file
    os.close(fd)
    print("File closed successfully!!")

When we run above program, it produces following result −

Read String is :  b'This is Tutorialspoint'
File closed successfully!!
python_files_io.htm
Advertisements