views:

36

answers:

2

This simple python code:

import mmap  

with file("o:/temp/mmap.test", "w+b") as fp:  
    m = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ|mmap.ACCESS_WRITE)  
    m.write("Hello world!")  

Produces the following error (on the mmap.mmap(...) line):
WindowsError: [Error 1006] The volume for a file has been externally altered so that the opened file is no longer valid

Any idea why?

+1  A: 

Most likely because w+ truncates the file, and Windows gives an error when trying to create an empty mapping from that file of length 0. Use r+ instead.

As well, you shouldn't use access=mmap.ACCESS_READ|mmap.ACCESS_WRITE:

>>> mmap.ACCESS_READ
1
>>> mmap.ACCESS_WRITE
2
>>> mmap.ACCESS_COPY
3
>>> mmap.ACCESS_READ | mmap.ACCESS_WRITE
3

In other words, access=mmap.ACCESS_READ|mmap.ACCESS_WRITE is the same as access=mmap.ACCESS_COPY. What you want is most likely access=mmap.ACCESS_WRITE, and on Windows that's what you get anyway if you don't explicitly use that argument.

Try this:

import mmap  

with file("o:/temp/mmap.test", "r+b") as fp:  
    m = mmap.mmap(fp.fileno(), 0)  
    m.write("Hello world!")  

( mmap docs: http://docs.python.org/library/mmap.html )

JAB
Tried r+, but it gives the same error. The access= is indeed redundant, but was added just to make sure it is not a strange way of windows to say 'permission denied'
Paul Oyster
@Paul - is the file populated with data? Length = 0 will only work with non-empty files. If you specify a length, then the file will be extended.
Jeremy Brown
All is well: the confusing part is the text of the error message (see my comment to Jeremy). I guess even an 'always look on the bright side of life' would be a better text for this error.
Paul Oyster
@Paul: especially if it made the computer whistle when thrown.
JAB
@JAB: goes without saying
Paul Oyster
+2  A: 

From the documentation:

If length is 0, the maximum length of the map is the current size of the file, except that if the file is empty Windows raises an exception (you cannot create an empty mapping on Windows).

You are opening the file with "w+" - the file is getting truncated... (size = 0)

Jeremy Brown
Yes, you are right. I was wandering about the weird text of the error-message, but just found out that 1006 is simply Win32's ERROR_FILE_INVALID that CreateFileMapping() produces...
Paul Oyster