二进制文件实际上只是一长串连续数据;您需要告诉np.fromfile()两者
去哪里找
和
什么类型的数据
期待。
如果您创建自己的文件,可能最容易理解:
import numpy as np
with open('numpy_testfile', 'w+') as f:
## we create a "header" line, which collects the lengths of all relevant arrays
## you can then use this header line to tell np.fromfile() *how long* the arrays are
dimensions=np.array([0,10,0,0,10,0,3,10],dtype=np.int32)
dimensions.tofile(f) ## write to file
a=np.arange(0,10,1) ## some fake data, length 10
a.tofile(f) ## write to file
print(a.dtype)
b=np.arange(30,40,1) ## more fake data, length 10
b.tofile(f) ## write to file
print(b.dtype)
## more interesting data, this time it's of type float, length 3
c=np.array([3.14,4.22,55.0],dtype=np.float64)
c.tofile(f) ## write to file
print(c.dtype)
a.tofile(f) ## just for fun, let's write "a" again
with open('numpy_testfile', 'r+b') as f:
### what's important to know about this step is that
# numpy is "seeking" the file automatically, i.e. it is considering
# the first count=8, than the next count=10, and so on
# as "continuous data"
dim=np.fromfile(f,dtype=np.int32,count=8)
print(dim) ## our header line: [ 0 10 0 0 10 0 3 10]
a=np.fromfile(f,dtype=np.int64,count=dim[1])## read the dim[1]=10 numbers
b=np.fromfile(f,dtype=np.int64,count=dim[4])## and the next 10
## now it's dim[6]=3, and the dtype is float 10
c=np.fromfile(f,dtype=np.float64,count=dim[6] )#count=30)
## read "the rest", unspecified length, let's hope it's all int64 actually!
d=np.fromfile(f,dtype=np.int64)
print(a)
print(b)
print(c)
print(d)
附录:
这个
numpy documentation
当涉及到
阻止使用
属于
np.tofile()
和
np.fromfile()
:
不要依赖tofile和fromfile的组合来存储数据,因为生成的二进制文件不是独立于平台的。特别是,不保存字节顺序或数据类型信息。数据可以以独立于平台的.npy格式存储,而不是使用save和load。
个人旁注:
如果你花了几天时间来理解这段代码,不要对学习感到气馁
python
;我们都从某个地方开始。我建议你诚实面对你给教授带来的障碍(如果这是在谈话中提到的),因为她/他在编程时应该能够正确地断言“你在哪里”。:-)