VOOZH about

URL: https://www.geeksforgeeks.org/python/file-locking-in-python/

⇱ File Locking in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

File Locking in Python

Last Updated : 23 Jul, 2025

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.

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.

Output

example.txt
Data
Locked operation
Data to be written
Comment