Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 804
Evan Fosmark Avatar asked Jan 28 '09 23:01

Evan Fosmark


2 Answers

Alright, so I ended up going with the code I wrote here, on my websitelink 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"):     # work with the file as it is now locked     print("Lock acquired.") 
like image 178
Evan Fosmark Avatar answered Sep 22 '22 08:09

Evan Fosmark


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.

like image 30
John Fouhy Avatar answered Sep 25 '22 08:09

John Fouhy