The Python Oracle

Locking a file in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:28 Accepted answer (Score 166)
00:52 Answer 2 (Score 51)
02:41 Answer 3 (Score 43)
03:12 Answer 4 (Score 25)
04:08 Thank you

--

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

Accepted answer links:
[here, on my website]: http://www.evanfosmark.com/2009/01/cross.../
[link is dead, view on archive.org]: https://web.archive.org/web/201405312037.../
[also available on GitHub]: https://github.com/dmfrey/FileLock

Answer 3 links:
[Portalocker]: https://pypi.python.org/pypi/portalocker

Answer 4 links:
[oslo.concurrency]: http://docs.openstack.org/developer/oslo.../
[Portalocker]: https://pypi.python.org/pypi/portalocker
[fasteners]: https://pypi.python.org/pypi/fasteners
[lockfile]: https://pypi.python.org/pypi/lockfile
[flufl.lock]: https://pypi.python.org/pypi/flufl.lock/...
[simpleflock]: https://github.com/derpston/python-simpl...
[zc.lockfile]: https://pypi.python.org/pypi/zc.lockfile?
[lock_file]: https://pypi.python.org/pypi/lock_file/2...

--

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