Ali
Ali

Reputation: 1533

Python : Check file is locked

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:

  1. the user does not have permission to the file or
  2. the file is locked by another process

How can I detect case (2) here?

(My target platform is Windows)

Upvotes: 15

Views: 32164

Answers (3)

paolov
paolov

Reputation: 2327

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

Upvotes: 6

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39718

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.

Upvotes: 3

Harman
Harman

Reputation: 1581

You can use os.access for checking your access permission. If access permissions are good, then it has to be the second case.

Upvotes: 7

Related Questions