将hdf5转换为.txt文件

时间:2019-07-12 03:42:00

标签: python numpy hdf5

我必须将import UIKit class CollectionViewCellCell: UICollectionViewCell { @IBOutlet weak var imageViewCell: UIImageView! } 文件转换为H5文件。我在Github上找到了可以转换相同代码的代码。我正在尝试输入自己的.txt文件。下面发布的代码给出了错误,并且无法转换。

Hdf5
R
python h5_txt.py thermal_images.h5
Make a numpy array
>>> np_array = np.random.random((30, 30))
Write it in h5 format
>>> h5_name = 'np_array.h5'
>>> write_dh5_np(h5_name, np_array)
Read it in h5 format and check contents
>>> np_array_from_h5 = read_hd5_np(h5_name)
>>> np.allclose(np_array_from_h5, np_array)
True
Write h5 file in txt format
>>> txt_name = 'np_array.txt'
>>> txt_name = convert_to_txt(h5_name, txt_name)
Read it in txt format and check contents
>>> np_array_from_txt = np.loadtxt(txt_name)
>>> np.allclose(np_array_from_txt, np_array)
True
  

Keyerror:“无法打开对象(对象'np_array'不存在)”

1 个答案:

答案 0 :(得分:0)

代码按预期工作。您可以按照以下步骤使其适合您。

创建文件mainfile.py并添加以下代码

import numpy as np
import helpers as h


np_array = np.random.random((30, 30));
h5_name = 'np_array.h5';
h.write_dh5_np(h5_name, np_array);
np_array_from_h5 = h.read_hd5_np(h5_name);
np.allclose(np_array_from_h5, np_array);
txt_name = 'np_array.txt'
txt_name = h.convert_to_txt(h5_name, txt_name)
np_array_from_txt = np.loadtxt(txt_name)
np.allclose(np_array_from_txt, np_array)

现在在同一文件夹中创建一个文件helpers.py,并在其中添加以下代码

import os
import sys
import doctest
import h5py
import numpy as np
def write_dh5_np(h5_name, np_array):
    """
    :param h5_name: Name of a h5 file
    :type h5_name: str
    :param np_array: Array of floats
    :type np_array: np.array
    """
    # assert not os.path.isfile(h5_name), "Won't overwrite {}".format(h5_name)

    with h5py.File(h5_name, 'w') as h5_file:
        h5_file.create_dataset('np_array', data=np_array)

def read_hd5_np(h5_name):
    """
    :param h5_name: Name of a h5 file
    :type h5_name: str

    :returns: Data in h5 file
    :rtype: np.array
    """
    with h5py.File(h5_name, 'r') as h5_file:
        np_array = h5_file['np_array'][()]

    return np_array

def convert_to_txt(h5_name, txt_name=None):
    """
    :param h5_name: Name of a h5 file
    :type h5_name: str
    :param txt_name: Name of a txt file to be created
    :type txt_name: str

    :returns: Name of a txt file that was created
    :rtype: str
    """
    if txt_name is None:
        strip_name = os.path.splitext(h5_name)[0]
        txt_name = '{}.txt'.format(strip_name)

    # assert not os.path.isfile(txt_name), "Won't overwrite {}".format(txt_name)

    np_array = read_hd5_np(h5_name)
    np.savetxt(txt_name, np_array)

    return txt_name

执行mainfile.py,您的代码将开始工作。 您没有将文件传递给实际上将hdf5文件转换为txt的方法,所以它给您一个错误。 希望对您有所帮助。