filelock

3.25.2 · active · verified Sat Mar 28

filelock is a platform-independent file locking library for Python that provides inter-process synchronization via OS-level primitives (fcntl on Unix, msvcrt on Windows) with automatic fallback to soft (file-existence) locking. It supports exclusive locks (FileLock, SoftFileLock), SQLite-backed read-write locks (ReadWriteLock, added in 3.21.0), and async variants (AsyncFileLock, AsyncReadWriteLock, added in 3.25.0). The current stable version is 3.25.2, released March 2026; the project ships multiple releases per month and requires Python ≥ 3.10.

Warnings

Install

Imports

Quickstart

Exclusive file lock with timeout; catch Timeout on contention.

from filelock import FileLock, Timeout

# Always lock a *separate* .lock file, not the file you intend to write.
lock = FileLock("data.txt.lock", timeout=10)

try:
    with lock:
        with open("data.txt", "a") as f:
            f.write("safe write\n")
except Timeout:
    print("Could not acquire lock within 10 seconds")

# Reentrant: acquiring the same lock object again inside the block is safe.
with lock:
    with lock:  # internal counter incremented; no deadlock
        pass

view raw JSON →