filelock
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
- breaking Python < 3.10 is no longer supported as of filelock 3.x modern releases. The requires-python constraint is >=3.10.
- gotcha Never lock the file you intend to write; create a separate companion .lock file. Locking the target file directly causes undefined behaviour because filelock may truncate or interfere with it.
- gotcha Timeout=None (the default) and timeout=-1 both mean 'block forever'. A timeout of 0 means exactly one non-blocking attempt. Passing timeout=0 does NOT mean 'no timeout'.
- gotcha SoftFileLock can leave stale lock files if a process crashes. On network/FUSE mounts where fcntl is unsupported, FileLock silently falls back to SoftFileLock (since 3.24.0), which is only stale-safe on same-host contention.
- breaking ReadWriteLock requires the lock file path to use a .db extension (it is backed by SQLite). Passing a plain .lock path raises an error.
- gotcha ReadWriteLock upgrading or downgrading lock mode (read→write or write→read) within the same thread raises RuntimeError. The lock is reentrant only within the same mode.
- deprecated The poll_intervall parameter (double-l spelling) in acquire() is deprecated in favour of poll_interval (single-l). Both are accepted for backward compatibility but the old spelling will eventually be removed.
Install
-
pip install filelock
Imports
- FileLock
from filelock import FileLock
- Timeout
from filelock import Timeout
- SoftFileLock
from filelock import SoftFileLock
- ReadWriteLock
from filelock import ReadWriteLock
- AsyncFileLock
from filelock import AsyncFileLock
- AsyncReadWriteLock
from filelock import AsyncReadWriteLock
Quickstart
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