Check if file is open by another process before open it

A file open in Windows specifies the allowed read/execute (1), write/append (2), and delete/rename (4) access sharing. The file’s share access is checked and updated atomically by the filesystem driver in the kernel, so there is no race condition.

If you don’t want to share write and delete access, then call CreateFile() with dwShareMode = FILE_SHARE_READ. If the file is currently open with FILE_WRITE_DATA, FILE_APPEND_DATA, or DELETE access, the open will fail with ERROR_SHARING_VIOLATION (32). Of course, turnabout is fair play, so if you’re requesting FILE_READ_DATA or FILE_EXECUTE access, and the file is currently open without read access sharing, the open will also fail with a sharing violation. If the open succeeds, then as long as the open exists (i.e. as long as the kernel file object has one or more handles), the file cannot be opened again with write, append, or delete (rename) access.

Python’s builtin open() shares read and write access, but not delete access. If you need a different share mode, you’ll have to call CreateFile directly via ctypes or PyWin32’s win32file module.