Python does not natively have a good function to check for file locks on Windows files. In many of my scripts it is important to check if a file is locked before working on it.
The function I wrote checks if there are two different locks on a file. The first checks if the file has a write lock. The second checks if the file has a read lock. A read lock allows you to read the file but you can't write to or delete the file.
The only way I found to check for a read lock is to rename the file and then quickly rename it back again. If the rename fails then the file has a read lock. This is a poor method to use to check for a lock. One, the code modifies the file instead of just "looking" at it. Two, if there were a failure during the rename, you could end up with a renamed file as the result.
If you know of a better way to check for a read lock, please let me know.
Here is the code:
def isFileLocked(file, readLockCheck=False):
'''
Checks to see if a file is locked. Performs three checks
1. Checks if the file even exists
2. Attempts to open the file for reading. This will determine if the file has a write lock.
Write locks occur when the file is being edited or copied to, e.g. a file copy destination
3. If the readLockCheck parameter is True, attempts to rename the file. If this fails the
file is open by some other process for reading. The file can be read, but not written to
or deleted.
@param file:
@param readLockCheck:
'''
if(not(os.path.exists(file))):
return False
try:
f = open(file, 'r')
f.close()
except IOError:
return True
if(readLockCheck):
lockFile = file + ".lckchk"
if(os.path.exists(lockFile)):
os.remove(lockFile)
try:
os.rename(file, lockFile)
sleep(1)
os.rename(lockFile, file)
except WindowsError:
return True
return False
Comments