API · Python

Python os.fsync() Function

Use Python's os.fsync() with file descriptors and buffered file objects, and understand its practical limits.

On this page

Python may buffer writes made through a file object, and the operating system may also cache file data. Calling os.fsync() asks the operating system to synchronize a file descriptor’s data and metadata with its storage device. This can reduce the amount of recently written data at risk after a crash, but it is not an unconditional guarantee against data loss: hardware, filesystems, and other system failures still matter.

os.fsync() is useful when an application needs to request that a completed write reach storage before it proceeds. It accepts a file descriptor, so a buffered Python file object must first be flushed and its descriptor retrieved with fileno().

What os.fsync() Does

The os.fsync() function requests synchronization of a file’s in-memory state with storage. It operates on the descriptor for an open file. It does not itself flush data still held in a Python file object’s user-space buffer, and it does not coordinate concurrent threads.

A successful call has no useful return value. If the operating system reports a problem, Python raises an OSError. Keep the descriptor open until the synchronization call has finished.

Syntax, Parameters, and Return Value

The function takes one argument, fd, an integer file descriptor, and returns None when the request completes successfully. Obtain a descriptor from a file object with file.fileno().

The essential sequence for buffered writes is file.write(...), file.flush(), then os.fsync(file.fileno()). flush() passes Python’s buffered data to the operating system; os.fsync() then requests synchronization for the underlying descriptor. Neither step should be described as an absolute promise that data survives every possible failure.

Use os.fsync() with a File Descriptor

Use os.open() when working directly with a descriptor. The following standalone example creates a temporary file, writes encoded bytes, requests synchronization, and closes the descriptor even if a later operation fails.

Run this example:

import os
import tempfile

content = b"I wish to write this information to the file."
with tempfile.TemporaryDirectory() as directory:
    path = os.path.join(directory, "data.txt")
    fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600)
    try:
        remaining = memoryview(content)
        while remaining:
            written = os.write(fd, remaining)
            remaining = remaining[written:]
        os.fsync(fd)
    finally:
        os.close(fd)
    with open(path, "rb") as file:
        print(file.read().decode())
I wish to write this information to the file.

The loop handles the possibility that a low-level write accepts fewer bytes than requested. The descriptor stays open through os.fsync() and is closed in the finally block. In the supplied run, the example exited with code 0 and printed the file content shown below.

Use os.fsync() with a File Object

For ordinary text handling, a file object is often more convenient. Call flush() before passing its descriptor to os.fsync(). A with block closes the file after the synchronization request.

Run this example:

import os
import tempfile

content = "I wish to write this information to the file."
with tempfile.TemporaryDirectory() as directory:
    path = os.path.join(directory, "data.txt")
    with open(path, "w", encoding="utf-8") as file:
        file.write(content)
        file.flush()
        os.fsync(file.fileno())
    with open(path, encoding="utf-8") as file:
        print(file.read())
I wish to write this information to the file.

Here, write() updates the Python buffer, flush() sends that buffer onward, and os.fsync() acts on the open file’s descriptor. In the supplied run, the example exited with code 0 and printed the file content shown below.

Use os.fsync() for Concurrent Logging

A lock can prevent threads in the same process from interleaving the critical part of their logging operation. The lock provides that coordination; os.fsync() does not make writes thread-safe. Synchronizing each record may also reduce throughput, so use this pattern only when the application’s durability needs justify the cost.

Run this example:

import os
import tempfile
import threading

entries = ["Log entry 1", "Log entry 2", "Log entry 3"]
lock = threading.Lock()

with tempfile.TemporaryDirectory() as directory:
    path = os.path.join(directory, "log.txt")

    def write_entry(entry):
        with lock:
            with open(path, "a", encoding="utf-8") as file:
                file.write(entry + "\n")
                file.flush()
                os.fsync(file.fileno())

    threads = [threading.Thread(target=write_entry, args=(entry,)) for entry in entries]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

    with open(path, encoding="utf-8") as file:
        print(file.read(), end="")
Log entry 1
Log entry 2
Log entry 3

Each thread takes the same lock before opening and appending its record, then flushes and synchronizes before releasing the lock. The records therefore appear as whole lines in this single-process example, though their order depends on thread scheduling. A lock in one process does not coordinate independent processes. In the supplied run, the example exited with code 0 and printed the three lines shown below.

Handle Bad File Descriptor Errors

OSError: [Errno 9] Bad file descriptor can occur when os.fsync() receives a descriptor that is no longer valid, such as one already closed. Keep the call before os.close() or before leaving the file object’s with block.

For a buffered file, the safe order is to write, flush, synchronize using file.fileno(), and then close. If an error is caught for diagnosis, inspect which descriptor was passed and whether its owning file is still open. Do not retry synchronization with a descriptor after closing it.

Limitations and Practical Guidance

Use os.fsync() when the application needs an explicit synchronization request after writing; avoid calling it after every small write unless that durability tradeoff is intentional. For buffered file objects, always flush first. For direct descriptors, check the return from os.write() when writing larger data, since a write can accept fewer bytes than requested.

Synchronizing a file does not necessarily synchronize a newly created, renamed, or removed directory entry. Some systems support opening and synchronizing the containing directory when that stronger filesystem-level behavior is needed, but the details and guarantees are platform-dependent. Consult the relevant operating system and filesystem documentation for that requirement.

The supplied runs for all three examples exited with code 0 and produced the outputs shown above. The key ordering remains: finish the write, flush any Python buffer, call os.fsync() while the descriptor is open, and then close it.