I want to lock the file whenever I perform read/write operation on that file. No other program or function can access file until I do not release the file. How do you do this in Python?
Asked
Active
Viewed 2,755 times
2 Answers
2
You can try this:
http://docs.python.org/library/fcntl.html#fcntl.flock
or this:
http://docs.python.org/library/fcntl.html#fcntl.lockf
To get file descriptor from a file-like object, you just need to call fileno
method.

gruszczy
- 40,948
- 31
- 128
- 181
-
Be careful with this. I would encourage use of a higher-level, well-debugged package because, absent deep thought, your use of these low-level functions is more likely to be imperfect. For example of a subtle race condition, look at the comment by Thomas Guettler here: http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ – Iron Pillow Jul 22 '14 at 00:18
-
This is mind-bending, too: http://stackoverflow.com/questions/9907616/python-fcntl-does-not-lock-as-expected – Iron Pillow Jul 22 '14 at 00:59
0
Google up zc.lockfile or portalocker.py. Both libraries can lock a file in a portable manner (windows and posix systems). I usually use zc.lockfile.

albertov
- 2,314
- 20
- 15
-
i used all library but any of them is not for my purpose. actually i want that whenever i read file no-one can read file and also write. – Lalit Chattar Jan 07 '11 at 13:52