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.")
filelock in action

Installation

filelock is available via PyPI:

python -m pip install filelock

Learn filelock

New to file locking?

Start with the Tutorials to learn the basics through hands-on examples.

Have a specific task?

Check How-to guides for task-oriented solutions to real-world problems.

Want to understand the design?

Read Concepts and design to explore design decisions and trade-offs.

Need API details?

See the API Reference reference for complete technical documentation.

Lock Types

Choose the right lock for your use case:

FileLock

Platform-aware alias. Selects a native backend where available and a soft marker otherwise.

  • ✓ Recommended default

  • ✓ Cancellable acquire

  • ✓ Self-deadlock detection

SoftFileLock

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

ReadWriteLock

SQLite-backed multiple readers + one writer. Singleton by default.

  • ✓ Concurrent readers

  • ✓ Reentrant per mode

  • ✓ Async via AsyncReadWriteLock

SoftReadWriteLock

Reader/writer marker lease for tested shared filesystems.

  • ✓ Heartbeat-based marker expiry

  • ✓ Writer preference

  • ✓ Explicit clock and filesystem requirements

  • ✓ Async via AsyncSoftReadWriteLock

AsyncFileLock

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

Windows

Uses LockFileEx on a byte range. Enforced by the kernel.

  • ✓ Native support

  • ✓ Most reliable

Unix / macOS

Uses fcntl.flock. Common on Unix but not POSIX; kernel-enforced.

  • ✓ Native support

  • ✓ Released automatically on crash

Other Platforms

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