Detect file is locked - windows

Hans Mulder hansmu at xs4all.nl
Wed Nov 14 09:55:15 CET 2012


On 14/11/12 02:14:59, Mark Lawrence wrote:
> 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.

I don't have a Windows machine at hand to try, but this might work:

    if exc.errno == 13:
        if os.access('file', os.W_OK):
            print "Locked by another process"
        else:
            print "No permission to write"

> Anything here help http://www.python.org/dev/peps/pep-3151/ ?

That won't help: in Python 3.3, IOError with errno==13 has been
replaced by PermissionError.  It still doesn't tell you *why*
you got a PermissionError.


Hope this helps,

-- HansM


More information about the Python-list mailing list