Fix Python – Locking a file in Python


Asked By – Evan Fosmark

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.

Now we will see solution for issue: Locking a file in Python


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

from filelock import FileLock

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

This question is answered By – Evan Fosmark

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0