以下是我尝试使用实例
强制执行的代码#Create a dtype to represent the header.
header_dtype = dtype([('rows', int32), ('cols', int32)])
# Create a memory mapped array using this dtype. Note the shape is empty.
header = memmap(file_name, mode='r', dtype=header_dtype, shape=())
# Read the row and column sizes from using this structured array.
rows = header['rows']
cols = header['cols']
# Create a memory map to the data segment, using rows, cols for shape
# information and the header size to determine the correct offset.
data = memmap(file_name, mode='r+', dtype=float64,shape=(rows, cols),
offset=header_dtype.itemsize)
我想用memmap阅读的文件格式是
我想知道当我尝试读取名为matrix.dat
的以下文件时出了什么问题4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
我在python中执行以下操作(Enthought的冠层编辑器)
header_dtype = dtype([('rows',int),('cols',int)])
header=memmap('matrix.dat',mode='r',dtype=header_dtype,shape=())
rows = header['rows']
cols=header['cols']
print header
(221519924, 840970506)
print rows cols
221519924, 840970506
为什么我没有得到4,4?如何更改上面显示的文件matrix.dat以正确读取数据?
答案 0 :(得分:1)
该文件被理解为二进制文件,因此前4个字节将为0x3420340d
,转换为221519924.您可能必须在文件中以二进制模式写入值。
对于文本文件,请改用numpy.loadtxt
;
In [1]: import numpy as np
In [2]: cat matrix.dat
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
In [3]: np.loadtxt('matrix.dat')
Out[3]:
array([[ 4., 4.],
[ 1., 2.],
[ 5., 6.],
[ 9., 10.],
[ 13., 14.]])