np.memmap读取大文件

Numpy中的ndarray是一种新形式的Python内建类型。所以,它能够在须要时被继承。ndarray造成了许多有用类的基础。
np.memmap就是其中一种,它是内存映射文件。本质上就是使用C语言中的fseek随机访问文件的任何一个位置执行读写操做。当一个特别大的数组没法常驻内存时,np.memmap很是有用。html

参数类型:python

  • filename:字符串、文件或者path
  • dtype:默认为uint8,表示每一个字节
  • mode:支持r+,r,w+,c四种文件打开方式,r表示只读方式打开文件爱你,r+表示可读可写,w+表示先覆盖一个已存在的文件而后可读可写,c表示能够对文件进行修改可是不会保存到磁盘。默认为r+。
  • offset:表示数组数据在文件中的偏移,此值应该是dtype类型的大小的整数倍。
  • shape:能够指定数组的维度,默认是一维数组。

memmap默认的文件打开方式是r+。数组

import numpy as np

a = np.random.randint(0, 10, (3, 4), dtype=np.int32)
print(a)
a.tofile("haha.bin")
b = np.memmap("haha.bin", dtype=np.int32, shape=(3, 4))
print(b)
b[0, 0] = 100
del b  # 关闭文件,自动调用数组的finalize函数
b = np.memmap("haha.bin", dtype=np.int32, shape=(3, 4))
print(b)

输出为:dom

[[7 7 7 3]
 [9 3 7 9]
 [0 7 8 8]]
[[7 7 7 3]
 [9 3 7 9]
 [0 7 8 8]]
[[100   7   7   3]
 [  9   3   7   9]
 [  0   7   8   8]]

参考资料

https://docs.scipy.org/doc/numpy/reference/arrays.classes.html函数

相关文章
相关标签/搜索