[python-win32] pure python way to open a file with write deny for others

Eryk Sun eryksun at gmail.com
Fri Mar 6 17:04:08 EST 2020


On 3/6/20, Robin Becker <robin at reportlab.com> wrote:
>
> OK I want to read the (small) file completely. The other process may try to
> re-write the file while I am reading it.

I thought the other process already had the file open for writing, but
apparently you just want to deny anyone the right to open the file
with write access while you're reading it. If the file is already open
with write access, you'll have to periodically retry opening it until
you can get read access without sharing write access.

Alternatively, you can use regular read-write sharing, but lock the
file data via msvcrt.locking. This doesn't deny opening the file for
write access, but any attempt to write to a locked region will fail
with a locking violation. The locked region can encompass the entire
file. (File locking in Windows doesn't prevent deleting or renaming a
file, but the default share mode already prevents that.)

> Of course the other process may adopt a completely orthogonal scheme of
> opening with a different name and then renaming,

Normally, open files in Python cannot be deleted or renamed until
they're closed. This is the case as long as you have the file opened
with just read or read-write sharing. Within the standard library,
only the low-level open flag O_TEMPORARY uses shared delete/rename
access.


More information about the python-win32 mailing list