What is the most elegant way to solve this:
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.
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 .
'r' – is the default that is used to open a file in read-mode only. 'r+' opens the file in read and write mode.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With