Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 291
mar10 Avatar asked Oct 09 '08 06:10

mar10


People also ask

How do I open an exclusive file?

Open the File in Exclusive ModeNavigate to the file, and select it. Click the down-arrow on the Open button to display a list of options. Select Open Exclusive .

How do I open a file as read only in Python?

'r' – is the default that is used to open a file in read-mode only. 'r+' opens the file in read and write mode.

Which method is used to open a file in Python?

Python provides two ways of opening files. The first method is by use of the open() function, however, this may not be the best way of opening files. The second and most preferred way is the use of the context manager.

Why is it best to open a file with with in Python?

With the “With” statement, you get better syntax and exceptions handling. “The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.” In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.


1 Answers

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.

like image 128
Brian Avatar answered Sep 19 '22 09:09

Brian