Why isn't mmap closing associated file (getting PermissionError: [WinError 32])?

Why isn't mmap closing associated file (getting PermissionError: [WinError 32])?

在试验 O'Reilly 网站 Reading Binary Data into a Mutable Buffer 部分的一些代码时,我在末尾添加了一行以删除创建的测试文件。

然而,这总是导致以下错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'data'

我不明白这种行为,因为 with memory_map(test_filename) as m: 应该隐式关闭关联文件,但显然没有。我可以通过保存从 os.open() 返回的文件描述符来解决这个问题,然后在 with 套件中的语句块完成后用 os.close(fd) 显式关闭它。

这是一个错误还是我遗漏了什么?

代码(有几行注释掉的代码显示了我的 hacky 解决方法):

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)

来自文档:

close()

Closes the mmap. Subsequent calls to other methods of the object will result in a ValueError exception being raised. This will not close the open file.

内存映射独立于文件句柄。您以后可以将文件句柄用作普通文件。