我需要将matlabfread翻译成python,特别是允许读取到2d数组,并在读取时跳过数据。 我想出了以下方法,但我想可能有更高效和“Python式”的方法(我绝不是程序员)。有什么建议吗?请注意,我无法读取整个文件,然后对数组进行子采样,因为要读取的文件太大。在
def FromFileSkip(fid, count=1, skip=0, dtype=np.float32):
if np.ndim(count)==0:
if skip>=0:
data = np.zeros(count, dtype=dtype)
k = 0
while k<count:
data[k] = np.fromfile(fid, count=1, dtype=dtype)
fid.seek(skip, 1)
k +=1
return data
elif np.ndim(count)==1:
if skip>0:
data = np.zeros(count, dtype=dtype)
k = 0
while k<count[1]:
data[:,k] = np.fromfile(fid, count=count[0], dtype=dtype)
fid.seek(skip, 1)
k +=1
return data
else:
raise ValueError('File can be read only into 1d or 2d arrays')
这或多或少是你的,只是稍微干净一点。在
相关问题 更多 >
编程相关推荐