为什么没有关闭关联文件(获取PermissionError:[WinError 32])?

时间:2017-11-02 20:16:02

标签: python windows python-3.x permissions mmap

在尝试使用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()返回的文件描述符来解决这个问题,然后在os.close(fd)套件中的语句块完成后用with显式关闭它。

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

代码(有几条注释掉的行显示我的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)

1 个答案:

答案 0 :(得分:2)

来自文档:

  

接近()

     

关闭mmap。对该对象的其他方法的后续调用将导致引发ValueError异常。这不会关闭打开的文件。

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