Managing a file is very important, particularly when multiple processes read and write to the same file. Using file locking we can prevent concurrent access to a file.

In this article, we will see how to lock a file using Python.

fcntl Module (Linux/Unix)

If you are using Linux/Unix, the fcntl module provides the flock function used to apply a lock to a file descriptor.

import fcntl

with open('myfile.txt', 'r+') as f:
    # Apply an exclusive lock
    fcntl.flock(f, fcntl.LOCK_EX)
    # Perform file operations
    # ...

    # Release the lock
    fcntl.flock(f, fcntl.LOCK_UN)

Here, LOCK_EX is an exclusive lock, which means no other process can access the file while it’s locked. LOCK_UN releases the lock.

msvcrt Module (Windows)

In Windows, we can use the msvcrt module which provides locking through locking function.

Following is the example:

import msvcrt

with open('myfile.txt', 'r+') as f:
    # Lock the file
    msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 10)
    # Perform file operations
    # ...

    # Unlock the file
    msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 10)

If you want a portable solution across all the operating systems then we can the portalocker library.

pip install portalocker
import portalocker

with open('myfile.txt', 'r+') as f:
    # Lock the file
    portalocker.lock(f, portalocker.LOCK_EX)

    # Perform file operations
    # The lock is automatically released on file close

In the above example, the open() function is used to open the file and the file will be locked using the lock() API of portalocker.

The lock will be automatically released once the file is closed.

Categorized in:

Tagged in: