os.path.getsize() on Windows

Duncan Booth duncan.booth at invalid.invalid
Wed Mar 19 08:34:34 EDT 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> This whole approach 
> assumes that Windows does the sensible thing of returning a unique 
error 
> code when you try to open a file for reading that is already open for 
> writing.
> 

So how would you use a file to share data then?

By default Python on Windows allows you to open a file for reading 
unless you specify a sharing mode which prevents it: the easiest way is 
probably to call win32file.CreateFile with appropriate parameters.

In one window:
>>> f = open('SHARE.txt', 'w')
>>> f.write('hello')
>>> f.flush()
>>>

and then while that other window is open:

>>> handle = win32file.CreateFile("SHARE.txt",
...     win32file.GENERIC_WRITE,
...     0, # i.e. "not shared" is the default
...     None,
...     win32file.OPEN_ALWAYS,
...     win32file.FILE_ATTRIBUTE_NORMAL,
...     None)
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
pywintypes.error: (32, 'CreateFile', 'The process cannot access the file 
because it is being used by another process.')
>>> f = open("SHARE.txt", "r")
>>> f.read()
'hello'

The CreateFile call was copied from 
http://mail.python.org/pipermail/python-list/2002-January/122462.html




More information about the Python-list mailing list