Python os.fsync() Method

Vaibhav Vaibhav Jan 30, 2023
  1. Syntax of Python os.fsync() Method
  2. Example 1: Use os.fsync() With a File Descriptor
  3. Example 2: Use os.fsync() With a File Object
Python os.fsync() Method

Python has an os module that gives access to various system calls and operating system methods. The fsync() method is a part of the os module and allows us to write a file to the disk forcefully.

Syntax of Python os.fsync() Method

os.fsync(fd)

Parameters

Type Description
fd integer A file descriptor associated with a valid resource.

Instead of a file descriptor, if the parameter is a file object, we must ensure that all the buffers linked with the passed file object are successfully written to the disk. Considering fd is the parameter name, we have to use fd.flush().

Subsequently, we can use os.fsync() as os.fsync(fd.fileno()) to forcefully save the file to the disk.

Returns

The fsync() method doesn’t return anything.

Example 1: Use os.fsync() With a File Descriptor

import os

fd = os.open("data.txt", os.O_RDWR | os.O_CREAT)
data = "I wish to write this information to the file."
os.write(fd, data.encode())  # write to the file
os.fsync(fd)  # forcefully writing to the file
os.close(fd)  # close the file descriptor

The Python code above creates a data.txt file if it doesn’t exist inside the current working directory. Next, it writes the encoded string data to the file, writes it to the disk, and closes the file descriptor.

Example 2: Use os.fsync() With a File Object

import os

f = open("data.txt", "w+")
data = "I wish to write this information to the file."
f.write(data)
f.flush()  # ensuring all the existing buffers are written
os.fsync(f.fileno())  # forcefully writing to the file
f.close()

The Python code above creates a data.txt file in the current working directory if it doesn’t exist. Afterward, it writes the data to the file.

Before forcefully saving it, we ensure that all the existing buffers associated with the file are written with the help of f.flush(). Lastly, os.fsync(f.fileno()) writes the file.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python OS