Python:检查文件已锁定

时间:2012-11-14 00:48:58

标签: python file-io

我的目标是知道文件是否被其他进程锁定,即使我无权访问该文件!

所以更清楚一点,假设我使用python的内置open()和'wb'开关(用于写入)打开文件。如果

,open()将抛出IOError与errno 13(EACCES)
  1. 用户无权访问该文件或
  2. 该文件被其他进程锁定
  3. 如何在这里检测案例(2)?

    我的目标平台是Windows!

3 个答案:

答案 0 :(得分:4)

您可以使用os.access来检查您的访问权限。如果访问权限很好,则必须是第二种情况。

答案 1 :(得分:4)

根据the docs:

errno.EACCES
    Permission denied
errno.EBUSY

    Device or resource busy

所以就这样做:

try:
    fp = open("file")
except IOError as e:
    print e.errno
    print e

从那里找出errno代码,然后设置。

答案 2 :(得分:1)

如先前评论中所建议,os.access无法返回正确的结果。

但是我在网上找到了另一个有效的代码。诀窍在于它尝试重命名文件。

来自: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