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. Selects a native backend where available and a soft marker otherwise.
✓ Recommended default
✓ Cancellable acquire
✓ Self-deadlock detection
Cooperative file-existence marker. Verify shared-filesystem semantics before deployment.
✓ No native locking API required
✓ Same-host PID inspection
✓ Optional age-based expiry, with overlap risk
SQLite-backed multiple readers + one writer. Singleton by default.
✓ Concurrent readers
✓ Reentrant per mode
✓ Async via AsyncReadWriteLock
Reader/writer marker lease for tested shared filesystems.
✓ Heartbeat-based marker expiry
✓ Writer preference
✓ Explicit clock and filesystem requirements
✓ Async via AsyncSoftReadWriteLock
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 LockFileEx on a byte range. Enforced by the kernel.
✓ Native support
✓ Most reliable
Uses fcntl.flock. Common on Unix but not POSIX; kernel-enforced.
✓ Native support
✓ Released automatically on crash
Automatic fallback to the cooperative SoftFileLock marker protocol.
✓ No native locking API required
✓ Usable where creation and cache behavior have been verified
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