Python : Check file is locked

2019-01-19 19:25发布

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 builtin 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!

2条回答
戒情不戒烟
2楼-- · 2019-01-19 19:51

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.

查看更多
叛逆
3楼-- · 2019-01-19 19:55

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

查看更多
登录 后发表回答