python - 如何使用python通过for循环将许多.npz文件转换为.mat文件
问题描述
我需要使用 python 将许多 .npz 文件转换为 .mat 文件。我的文件的排列方式类似于 datafile_1.npz、datafile_2.npz 等我想将它们转换为 datafile_1.mat、datafile_2.mat 文件等。目前我写了一个代码但出现错误 AttributeError: 'str' object has no attribute'项目'...为什么我无法理解这个错误。我希望有人能提供帮助。
import numpy as np
import scipy.io
import glob
filpath=glob.glob('./datafile_*.npz')
for file in filpath:
#data = np.load('file',)
scipy.io.savemat('filepath'+'.mat', mdict=file)
print(data)
解决方案
有了npz
我之前的SO:
In [491]: data = np.load('test.npz')
In [492]: list(data.keys())
Out[492]: ['arr_0', 'arr_1', 'arr_2']
In [493]: data['arr_0']
Out[493]:
array([[1., 1., 1.],
[1., 1., 1.]])
In [494]: data['arr_1']
Out[494]:
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
In [495]: data['arr_2']
Out[495]:
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
data
是一个dict
相似的对象。所以它实际上可以作为mdict
参数传递给savemat
(也需要一个字典):
In [496]: io.savemat('data.dat', data)
测试保存:
In [497]: io.loadmat('data.dat')
Out[497]:
{'__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Sun Aug 2 17:16:18 2020',
'__version__': '1.0',
'__globals__': [],
'arr_0': array([[1., 1., 1.],
[1., 1., 1.]]),
'arr_1': array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]),
'arr_2': array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])}
或者我们可以制作自己的字典
In [498]: io.savemat('data.dat', mdict={'x':data['arr_0'], 'y':data['arr_1']})
In [499]: io.loadmat('data.dat')
Out[499]:
{'__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Sun Aug 2 17:19:06 2020',
'__version__': '1.0',
'__globals__': [],
'x': array([[1., 1., 1.],
[1., 1., 1.]]),
'y': array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])}
关键是要了解np.load
对于npz
return dict
,我们可以从中加载实际的数组。这dict
本身不是数据。同样savemat
需要 a dict
of 数组。由于两者都使用 dicts,我们不必显式加载数组。
推荐阅读
- mono - 在 xfce 中设置 monodevelop
- keras - model.fit 期间 Keras 中的尺寸不匹配
- arrays - 如何将一个对象插入到mongo数组中的另一个对象中
- css - 材质单元格不会完全改变背景颜色
- ios - ConfigData 框架在上传到 Apple Store 时未编译
- r - Rstudio pandoc问题
- regex - 正则表达式使用 Negative Lookahead 和 Negative Lookbehind 在多行 xml 中捕获字符串
- node.js - 使用 express 向客户端发送 cookie 不起作用
- linux - 如何使用 Bash 测试 hdfs 文件是否存在
- python - sess.run 在一个循环中