While experimenting with some of the code from the Reading Binary Data into a Mutable Buffer section of the O'Reilly website, I added a line at the end to remove the test file that was created.
However this always results in the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'data'
I don't understand this behavior because the with memory_map(test_filename) as m:
should implicitly close the associated file, but apparently doesn't. I can work around this by saving the file descriptor returned from os.open()
and then explicitly closing it with an os.close(fd)
after the block of statements in the with
suite finishes.
Is this a bug or have I missed something?
Code (with the couple of commented-out lines showing my hacky workaround):
import os
import mmap
test_filename = 'data'
def memory_map(filename, access=mmap.ACCESS_WRITE):
# global fd # Save to allow closing.
size = os.path.getsize(filename)
fd = os.open(filename, os.O_RDWR)
return mmap.mmap(fd, size, access=access)
# Create test file.
size = 1000000
with open(test_filename, 'wb') as f:
f.seek(size - 1)
f.write(b'\x00')
# Read and modify mmapped file in-place.
with memory_map(test_filename) as m:
print(len(m))
print(m[0:10])
# Reassign a slice.
m[0:11] = b'Hello World'
# os.close(fd) # Explicitly close the file descriptor -- WHY?
# Verify that changes were made
print('reading back')
with open(test_filename, 'rb') as f:
print(f.read(11))
# Delete test file.
# Causes PermissionError: [WinError 32] The process cannot access the file
# because it is being used by another process: 'data'
os.remove(test_filename)