Search code examples
pythonfile-locking

Locking a file in Python


I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.


Solution

  • Update as of June 2024

    Nowadays there seem to be a number of robust, cross-platform, actively-maintained solutions to this. A few of the most cited in other answers and comments are:

    Original Answer

    Alright, so I ended up going with the code I wrote here, on my website link is dead, view on archive.org (also available on GitHub). I can use it in the following fashion:

    from filelock import FileLock
    
    with FileLock("myfile.txt.lock"):
        # work with the file as it is now locked
        print("Lock acquired.")