The Python Oracle

Locking a file in Python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 Locking A File In Python
00:20 Accepted Answer Score 172
00:42 Answer 2 Score 56
01:57 Answer 3 Score 44
02:22 Answer 4 Score 26
03:14 Answer 5 Score 18
03:24 Thank you

--

Full question
https://stackoverflow.com/questions/4898...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #filelocking

#avk47



ACCEPTED ANSWER

Score 177


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.")



ANSWER 2

Score 45


There is a cross-platform file locking module here: Portalocker

Although as Kevin says, writing to a file from multiple processes at once is something you want to avoid if at all possible.

If you can shoehorn your problem into a database, you could use SQLite. It supports concurrent access and handles its own locking.




ANSWER 3

Score 27


I have been looking at several solutions to do that and my choice has been oslo.concurrency

It's powerful and relatively well documented. It's based on fasteners.

Other solutions:




ANSWER 4

Score 18


I prefer lockfile — Platform-independent file locking