使用mmap打开文件失败

时间:2017-05-24 16:43:41

标签: python windows python-2.7 mmap

Windows上的Python 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')

现在它工作正常。我现在做得对吗?

1 个答案:

答案 0 :(得分:0)

是的,就是这样,感谢所有人!

# -*- 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')