pythonpython-2.7filelock

python filelock module deleting files


I have downloaded the filelock module in order to lock files using my python program. this is my code:

import filelock
lock = filelock.FileLock(path)
lock.acquire()
#do something...
lock.release()

for some reason I don't understand when I release the lock the file is deleted. Does anyone know how to deal with this? How can I keep the file available also after the lock is released? if it is relevant, my file is kept on a separate hard drive. thank you.

I am using windows 10 pro


Solution

  • I am not sure why but the documentation suggests that it should not do what you are experiencing. However if you are using this on windows, you can look at the implementation of release lock and you will realise that it will indeed delete the file if it is the final lock or if the lock is forcefully released. Please have a look at the section for the "Windows locking mechanism".

    The underlying implementation for windows locking uses the following release code:

    def _release(self):
        msvcrt.locking(self._lock_file_fd, msvcrt.LK_UNLCK, 1)
        os.close(self._lock_file_fd)
        self._lock_file_fd = None
    
        try:
            os.remove(self._lock_file)
        # Probably another instance of the application
        # that acquired the file lock.
        except OSError:
            pass
        return None
    

    As you can see the os.remove will delete the file. Even though this does not help but hopefully explains why this is happening. Could be a bug or stale code somebody forgot to remove.