filelock¶
A platform-independent file locking library for Python, providing inter-process synchronization:
from filelock import FileLock
lock = FileLock("high_ground.txt.lock")
with lock:
with open("high_ground.txt", "a") as f:
f.write("You were the chosen one.")
Installation¶
filelock is available via PyPI:
python -m pip install filelock
Learn filelock¶
Start with the Tutorials to learn the basics through hands-on examples.
Check How-to guides for task-oriented solutions to real-world problems.
Read Concepts and design to explore design decisions and trade-offs.
See the API Reference reference for complete technical documentation.
Lock Types¶
Choose the right lock for your use case:
Platform-aware alias. Uses OS-level locking (fcntl/msvcrt) with automatic fallback to soft locks.
✓ Recommended default
✓ Lifetime expiration, cancellable acquire
✓ Self-deadlock detection
File-existence based locking. Works on any filesystem including network mounts.
✓ Network filesystems
✓ Stale detection (Unix)
✓ Lifetime expiration, cancellable acquire
SQLite-backed multiple readers + one writer. Singleton by default.
✓ Concurrent readers
✓ Reentrant per mode
✓ Async via AsyncReadWriteLock
Async-compatible variants. Run blocking I/O in thread pool or custom executor.
✓ Async/await support
✓ All lock types
✓ Custom executor and event loop
Platform Support¶
Uses msvcrt.locking. Enforced by the kernel.
✓ Native support
✓ Most reliable
Uses fcntl.flock. POSIX standard, kernel-enforced.
✓ Native support
✓ Stale detection
Automatic fallback to SoftFileLock. Portable across all filesystems.
✓ Full compatibility
✓ Network filesystems
Similar libraries¶
pid - process ID file locks
msvcrt - Windows file locking (stdlib)
fcntl - Unix file locking (stdlib)
flufl.lock - Another file locking library
fasteners - Cross-platform locks and synchronization