首页 > 解决方案 > 如何使用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)
    
 

标签: pythonmatlabnumpyfor-loopscipy

解决方案


有了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对于npzreturn dict,我们可以从中加载实际的数组。这dict本身不是数据。同样savemat需要 a dictof 数组。由于两者都使用 dicts,我们不必显式加载数组。


推荐阅读