在Google Colab中从github读取.mat文件

时间:2019-02-11 10:31:35

标签: python google-colaboratory

我想从github链接(https://github.com/pranavn91/APS/blob/master/data.mat)中读取.mat文件,并将其存储到变量中。我正在使用python3和google colab。

第一种方法:

!wget  http://upscfever.com/upsc-fever/en/data/deeplearning2/images/data.mat  -P drive/app
 f = h5py.File("drive/app/data.mat", "r")   
data = f.get('data/variable1') 
data = np.array(data) 

第二种方法:FileNotFoundError,但文件url正确

url = 'https://github.com/pranavn91/APS/blob/master/data.mat'
import scipy.io
mat = scipy.io.loadmat(url)

错误:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/scipy/io/matlab/mio.py in _open_file(file_like, appendmat)
     32     try:
---> 33         return open(file_like, 'rb'), True
     34     except IOError:

FileNotFoundError: [Errno 2] No such file or directory: 'https://github.com/pranavn91/APS/blob/master/data.mat'

During handling of the above exception, another exception occurred:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-2-ee625cac9f79> in <module>()
      1 url = 'https://github.com/pranavn91/APS/blob/master/data.mat'
      2 import scipy.io
----> 3 mat = scipy.io.loadmat(url)

/usr/local/lib/python3.6/dist-packages/scipy/io/matlab/mio.py in loadmat(file_name, mdict, appendmat, **kwargs)
    139     """
    140     variable_names = kwargs.pop('variable_names', None)
--> 141     MR, file_opened = mat_reader_factory(file_name, appendmat, **kwargs)
    142     matfile_dict = MR.get_variables(variable_names)
    143     if mdict is not None:

/usr/local/lib/python3.6/dist-packages/scipy/io/matlab/mio.py in mat_reader_factory(file_name, appendmat, **kwargs)
     62 
     63     """
---> 64     byte_stream, file_opened = _open_file(file_name, appendmat)
     65     mjv, mnv = get_matfile_version(byte_stream)
     66     if mjv == 0:

/usr/local/lib/python3.6/dist-packages/scipy/io/matlab/mio.py in _open_file(file_like, appendmat)
     37             if appendmat and not file_like.endswith('.mat'):
     38                 file_like += '.mat'
---> 39             return open(file_like, 'rb'), True
     40         else:
     41             raise IOError('Reader needs file name or open file-like object')

FileNotFoundError: [Errno 2] No such file or directory: 'https://github.com/pranavn91/APS/blob/master/data.mat'

1 个答案:

答案 0 :(得分:2)

这是一个例子:

https://colab.research.google.com/drive/1GGyNoKYHECmf-vlH3AZdTsGjKgttaSkY

相关位:

# raw=true is important so you download the file rather than the webpage.
!wget https://github.com/pranavn91/APS/blob/master/data.mat?raw=true
# rename the file
!mv data.mat\?raw\=true data.mat
# update scipy
!pip install -U -q scipy
# Load the data
from scipy import io
v = io.loadmat('data.mat')