使用 mmap 打开文件失败

Open file with mmap fails

Python Windows 2.7。尝试使用 mmap 模块,但使用打开文件处理程序而不是 with open(filename, "r+b") as f: 我只是打开它并得到一个 WindowsError [Error 5].

它确实会重现,无论是否以 运行 管理员身份。 使用 codecs.open() 无法解决问题。

# -*- coding: utf8 -*-
from __future__ import print_function
import mmap

class QSHFile(object):
    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename, 'r')
        self.fileno = self.file.fileno()
        self.mm = mmap.mmap(self.fileno, 0)
        print(self.mm[:5])  # prints first 5


if __name__ == '__main__':
    qsh = QSHFile('example.qsh')

经过一番研究,我得出:

#! /usr/bin/python
# -*- coding: utf8 -*-
from __future__ import print_function
from mmap import ACCESS_READ, mmap

class QSHFile(object):
    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename, 'rb')
        self.fileno = self.file.fileno()
        self.mm = mmap(self.fileno, 0, access=ACCESS_READ)
        print(self.mm[:5])

if __name__ == '__main__':
    qsh = QSHFile('example.qsh')

现在一切正常。我现在做得对吗?

对,就这样,谢谢大家!

# -*- coding: utf8 -*-
from __future__ import print_function
from mmap import ACCESS_READ, mmap
from binascii import hexlify as hex

class QSHFile(object):
    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename, 'rb')
        print('File [%s] opened' % self.filename)
        self.fileno = self.file.fileno()
        self.mm = mmap(self.fileno, 0, access=ACCESS_READ)
        print('File size: %s bytes' % self.mm.size())
        print(hex(self.mm[:5]))


if __name__ == '__main__':
    qsh = QSHFile('example.qsh')