How To Open a File in Python Without Locking It

by Davide Mastromatteo
1 minute read


When I use python I’m usually on Linux or macOS but last week I had to write a python script on Windows.
Yes, Windows! You know… that place where slashes are misoriented, drives are named with a single alphabet letter and “tail” and “grep” commands are usually considered less important than “Clippy”.

clippy{: .align-center}

However, working on windows I’ve discovered something I considered weird: opening a file on Windows with the open() method, actually locks the file and prevents it from deletion. So, while this is being executed…

1for line in open(prova.log):
2    print(line)

… you can’t delete the “prova.log” file.

But this doesn’t happen on Linux or macOS. So, if you need to open a file without locking it, you need to use Mark Hammond’s pypiwin32, the Python extensions for Microsoft Windows that provide access to much of the Win32 API.

In fact, by using the Win32 API you can …

 1import os
 2import win32file
 3import msvcrt
 5filename = prova.log
 7# get an handle using win32 API, specifyng the SHARED access!
 8handle = win32file.CreateFile(filename,
 9                                win32file.GENERIC_READ,
10                                win32file.FILE_SHARE_DELETE |
11                                win32file.FILE_SHARE_READ |
12                                win32file.FILE_SHARE_WRITE,
13                                None,
14                                win32file.OPEN_EXISTING,
15                                0,
16                                None)
18# detach the handle
19detached_handle = handle.Detach()
21# get a file descriptor associated to the handle
22file_descriptor = msvcrt.open_osfhandle(
23    detached_handle, os.O_RDONLY)
25# open the file descriptor
26file = open(file_descriptor)
28for line in file:
29    print(line)

… you can delete the file while you are reading from it.

That’s cool, isn’t it?

Happy coding!

Did you find this article helpful?