Open In App

File Locking in Python

Last Updated : 29 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

File locking in Python is a technique used to control access to a file by multiple processes or threads. In this article, we will see some generally used methods of file locking in Python.

What is File Locking in Python?

File locking in Python is a technique used to control access to a file by multiple processes and ensures that only one process or thread can access the file at any given time, preventing conflicts and data corruption. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling operations, to operate on files.

File Locking in Python

Below, are the code examples of File Locking in Python:

  • Using fcntl Module
  • Using threading Module

File Structure

file-lock

example.txt

Data

Example 1: File Locking Using fcntl Module

In this example, below Python code demonstrates file locking using the `fcntl` module. It opens a file named “example.txt” in append mode, acquires an exclusive lock to prevent simultaneous access, writes data to the file, and then releases the lock to allow other processes to access it safely.

Python3
import fcntl

file_path = "example.txt"

# Open the file in write mode
with open(file_path, "a") as file:
    # Acquire exclusive lock on the file
    fcntl.flock(file.fileno(), fcntl.LOCK_EX)

    # Perform operations on the file
    file.write("Data to be written\n")

    # Release the lock
    fcntl.flock(file.fileno(), fcntl.LOCK_UN)

Output

example.txt
Data
Locked operation
Data to be written

Example 2: File Locking Using threading Module

In this example, below This Python code uses threading to concurrently write data to a file named “example.txt” while ensuring thread safety. It creates a lock using threading.Lock() to synchronize access, then spawns five threads, each executing the write_to_file() function.

Python3
import threading

file_path = "example.txt"
lock = threading.Lock()

def write_to_file():
    with lock:
        with open(file_path, "a") as file:
            file.write("Data to be written\n")

# Create multiple threads to write to the file
threads = []
for _ in range(5):
    thread = threading.Thread(target=write_to_file)
    thread.start()
    threads.append(thread)

# Wait for all threads to complete
for thread in threads:
    thread.join()

Output

example.txt
Data
Locked operation
Data to be written

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads