![]() |
VOOZH | about |
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.
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.
Below, are the code examples of File Locking in Python:
fcntl Module threading ModuleFile Structure
example.txt
Datafcntl 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
threading ModuleIn 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