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

Robin Becker robin at reportlab.com
Mon Mar 9 05:17:15 EDT 2020


On 06/03/2020 22:04, Eryk Sun wrote:
> 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.
> 
yes we poll periodically for late mod time files and try to post these to a web server. If there are misreads we hope 
that the next poll will find them not being written. After some of the thoughts posted here I suspect we probably ought 
not to try to prevent the other process writing. What we are really trying to do is get a snapshot of files which have 
changed since our last poll read. The real problem is to ensure that the content read is not partial ie was not being 
written at the time of read.


> 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.)
unfortunately I cannot assume they are appending so partial locking is probably not useful.

> 
>> 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.
> 


-- 
Robin Becker


More information about the python-win32 mailing list