Python OS file/directory os.fsync() method

Python OS File/Directory os.fsync() Method

Description

The fsync() method writes the file corresponding to file descriptor fd to disk. If you have a Python file object f, first execute f.flush() and then execute os.fsync(f.fileno()) to ensure that all internal buffers associated with f are flushed to disk.

Syntax

The syntax of the fsync() method is as follows −

os.fsync(fd)

Parameters

  • fd – This is the file descriptor whose buffers need to be synchronized.

Return Value

This method does not return any value.

Example

The following example shows the usage of the fsync() method:

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

# Write one string
line="this is test"
b=line.encode()
os.write(fd, b)

# Now you can use fsync() method.
# Infact here you would not be able to see its effect.
os.fsync(fd)

# Now read this file from the beginning
os.lseek(fd, 0, 0)
line = os.read(fd, 100)
b=line.decode()
print ("Read String is : ", b)

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

When running the above program, it will produce the following output –

Read String is: this is test
Closed the file successfully!!

Leave a Reply

Your email address will not be published. Required fields are marked *