My goal is to know if a file is locked by another process or not, even if I don't have access to that file!
So to be more clear, let's say I'm opening the file using python's built-in open()
with 'wb'
switch (for writing). open()
will throw IOError
with errno 13 (EACCES)
if:
How can I detect case (2) here?
(My target platform is Windows)
You can use os.access
for checking your access permission. If access permissions are good, then it has to be the second case.
As suggested in earlier comments, os.access
does not return the correct result.
But I found another code online that does work. The trick is that it attempts to rename the file.
From: https://blogs.blumetech.com/blumetechs-tech-blog/2011/05/python-file-locking-in-windows.html
def isFileLocked(filePath):
'''
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. 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 filePath:
'''
if not (os.path.exists(filePath)):
return False
try:
f = open(filePath, 'r')
f.close()
except IOError:
return True
lockFile = filePath + ".lckchk"
if (os.path.exists(lockFile)):
os.remove(lockFile)
try:
os.rename(filePath, lockFile)
sleep(1)
os.rename(lockFile, filePath)
return False
except WindowsError:
return True
According to the docs:
errno.EACCES
Permission denied
errno.EBUSY
Device or resource busy
So just do this:
try:
fp = open("file")
except IOError as e:
print e.errno
print e
Figure out the errno code from there, and you're set.
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