打开用于编写和读取大文件Python

时间:2016-12-12 12:20:05

标签: python file large-files

我尝试使用os.openmmapfrom_buffer()来阅读大型二进制文件(> 5 GB)。

正在运行fd = os.open(filePath, O_RDWR)错误OSError: [Errno 22] Invalid argument: H:\\xyz.wdp。我意识到问题是文件太大,因为使用类似但较小的文件O_WRONLYO_RDONLY,它可以工作。 很遗憾,如果我使用O_WRONLYO_RDONLY,则from_buffer()函数(TypeError: mmap can't modify a readonly memory map.)的访问权将被拒绝。

我的示例代码是:

class StructData(Structure):
    _pack_ = 1
    _fields_ = [('bin', c_ubyte)]

fd = os.open(filePath, os.O_RDWR)
mmap_file = mmap.mmap(fd, length=80, access=mmap.ACCESS_WRITE, offset=0)
d_array = StructData*80
data = d_array.from_buffer(mmap_file)

你能帮我解决这个问题吗?我想添加大文件,我需要它运行得非常快,我想避免使用struct.unpack等等。

谢谢!

1 个答案:

答案 0 :(得分:1)

从路径上看,您似乎正在使用Windows。 文档(https://docs.python.org/2/library/os.html#os.open)表示应该使用os.O_BINARY在Windows上以二进制模式打开文件。 你试过以下吗? (如果您可能正在创建文件......)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
        // use the field Uri, it now points to the path to the image taken from the camera.
    }
}

我不知道Windows中有关大文件支持的情况: https://docs.python.org/2/library/posix.html