What is the best way to open a file for exclusive access in Python?

mar10 picture mar10 · Oct 9, 2008 · Viewed 50.9k times · Source

What is the most elegant way to solve this:

  • open a file for reading, but only if it is not already opened for writing
  • open a file for writing, but only if it is not already opened for reading or writing

The built-in functions work like this

>>> path = r"c:\scr.txt"
>>> file1 = open(path, "w")
>>> print file1
<open file 'c:\scr.txt', mode 'w' at 0x019F88D8>
>>> file2 = open(path, "w")
>>> print file2
<open file 'c:\scr.txt', mode 'w' at 0x02332188>
>>> file1.write("111")
>>> file2.write("222")
>>> file1.close()

scr.txt now contains '111'.

>>> file2.close()

scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).

The solution should work inside the same process (like in the example above) as well as when another process has opened the file.
It is preferred, if a crashing program will not keep the lock open.

Answer

Brian picture Brian · Oct 9, 2008

I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module.

Fortunately, there is a portable implementation (portalocker) using the platform appropriate method at the python cookbook.

To use it, open the file, and then call:

portalocker.lock(file, flags)

where flags are portalocker.LOCK_EX for exclusive write access, or LOCK_SH for shared, read access.