Detect file is locked - windows

Tim Golden mail at
Wed Nov 14 12:50:49 CET 2012

On 14/11/2012 00:33, Ali Akhavan wrote:
> I am trying to open a file in 'w' mode open('file', 'wb'). open()
> will throw with IOError with errno 13 if the file is locked by
> another application or if user does not have permission to open/write
> to the file.
> How can I distinguish these two cases ? Namely, if some application
> has the file open or not.

The Python io module calls into the MS CRT, which maps both errors
which is 13.

If you really need to distinguish the two situations, you'll need to
call CreateFile directly (via ctypes or the pywin32 modules or an
extension module) and then call GetLastError() to get the specific

You're far better off using this EAFP approach as, even if it were
simple to determine beforehand whether a file can be locked or read --
and it's not -- that situation could have changed by the time you
actually come to open it.

Once you've successfully got a handle to the file, that handle is valid
regardless of any later changes to the file's security.


More information about the Python-list mailing list