【发布时间】:2018-04-15 11:40:46
【问题描述】:
在尝试使用 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)
【问题讨论】:
标签: python windows python-3.x permissions mmap