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. Uses OS-level locking (fcntl/msvcrt) with automatic fallback to soft locks.

  • ✓ Recommended default

  • ✓ Lifetime expiration, cancellable acquire

  • ✓ Self-deadlock detection

SoftFileLock

File-existence based locking. Works on any filesystem including network mounts.

  • ✓ Network filesystems

  • ✓ Stale detection (Unix)

  • ✓ Lifetime expiration, cancellable acquire

ReadWriteLock

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

  • ✓ Concurrent readers

  • ✓ Reentrant per mode

  • ✓ Async via AsyncReadWriteLock

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 msvcrt.locking. Enforced by the kernel.

  • ✓ Native support

  • ✓ Most reliable

Unix / macOS

Uses fcntl.flock. POSIX standard, kernel-enforced.

  • ✓ Native support

  • ✓ Stale detection

Other Platforms

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